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.