0

My input data file abc.txt has this

"20131008","0004","0568","98"

I ran this command to replace the text

nawk -F, -vOFS=',' '{gsub("0568","0808",$3); print }' abc.txt

In the output the delimiter "," is replaced with a space. The output looks like this.

 "20131008" "0004" "0568" "98".

Can someone please help with this? I tried to replace the -vOFS but doesn't work.

  • What is your OS and nawk version? – cuonglm Aug 19 '14 at 1:34
  • This is because you use -vOFS=','. You need a space between -v and OFS=','. – fedorqui Aug 19 '14 at 9:29
1

This answer demonstrate awk and sed examples, both in command line output and in file changes.

For awk, we'll use $ awk -F"," '{gsub("0568", "0808", $3)}1' input.txt and receive the changed string in command line output (or to variable), but the original file will not change.

$ cat input.txt 
"20131008","0004","0568","98"
$ awk -F"," '{gsub("0568", "0808", $3)}1' input.txt
"20131008" "0004" "0808" "98"

For sed, we'll use simple form sed -i 's/string to replace/new string/g' input.txt where -i flag is for changes in place (i.e. modifying the original file).

$ cat input.txt 
"20131008","0004","0568","98"
$ sed -i 's/0568/0808/g' input.txt
$ cat input.txt 
"20131008","0004","0808","98"

Although it's not what you asked for in nawk (I don't have it installed), I hope you'll find it helpful.

1

I don't have nawk but this works for me (with gawk, using the --posix switch):

awk 'BEGIN{FS=OFS=","}{sub(/0568/,"0808",$3)}1' file

fedorqui's comment suggests that you may need to use -v OFS=',' rather than -vOFS=',' but if input and output separator are the same, the assignment in the BEGIN block isn't much longer. I've also changed your gsub to sub as it looks like you're only looking to make one substitution. The first argument to either function is a regular expression so you shouldn't pass it a string.

Output:

"20131008","0004","0808","98"
-1

I tried this:

nawk 'BEGIN { FS=OFS="," } { sub("0568","0808",$3) }1' abc.txt

It works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.