Modify specified columns in awk

Source: Internet
Author: User

Modify specified columns in awk

An error occurred while handling text files.

Cat test.txt

"355356" "1700870" "1" "0202 """
"355356" "1700871" "2" 02046"
"355356" "1700870" 2 "" 02046"
"1700870" "1700873" 1 "" 0202"
Change the data of 2nd columns to 1700870

At first, I had to use sed directly,

Sed-I "s, 1700870,1700888, g" test.txt

The data obtained is as follows. At first, I thought this method was correct, but later I found that I had made a silly mistake. The last field in the first column is also replaced.

"355356" "1700888" "1" "0202 """
"355356" "1700871" "2" 02046"
"355356" "1700888" 2 "" 02046"
"1700888" "1700873" 1 "" 0202"

Later, awk was used to solve this problem.

The idea is to process rows with the second column equal to 1700870.

Awk-F "\" "'{if ($4 = 1700870) $4 = 1700888}' test.txt
I did not print any results. I searched the internet and tried to print the processed text either using print or adding 1 at the end, as shown below:

Awk-F "\" "'{if ($4 = 1700870) $4 = 1700888} 1' test.txt

The result is as follows:

355356 1700888 1 0202
"355356" "1700871" "2" 02046"
355356 1700888 2 02046
"1700870" "1700873" 1 "" 0202"
I don't know why "no", and the exact rule does not comply with the rules, because when awk processes each row of data, it will replace the output separator with the default "space", so we find that each

No rows have been processed.

After searching for the usage of awk, you can specify the output separator yourself during the output.

Awk-F "\" "'{OFS =" \ ""} {if ($4 = 1700870) $4 = 1700888} 1 'test.txt

The result is as follows:

"355356" "1700888" "1" "0202 """
"355356" "1700871" "2" 02046"
"355356" "1700888" 2 "" 02046"
"1700870" "1700873" 1 "" 0202"

However, the above awk syntax is too ugly, so let's improve it.

Awk 'in in {FS = OFS = "\" "} {if ($4 = 1700870) $4 = 1700888} 1' test.txt
Put the defined input and output characters in BEGIN to enhance the readability of the program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.