0

I have semicolon-separated columns, and I would like to add some characters to a specific column.

aaa;111;bbb
ccc;222;ddd
eee;333;fff

to the second column I want to add '@', so the output should be;

aaa;@111;bbb
ccc;@222;ddd
eee;@333;fff

I tried

awk -F';' -OFS=';' '{ $2 = "@" $2}1' file

It adds the character but removes all semicolons with space.

3 Answers 3

1

You could use sed to do your job:

# replaces just the first occurrence of ';', note the absence of `g` that 
# would have made it a global replacement
sed 's/;/;@/' file > file.out

or, to do it in place:

sed -i 's/;/;@/' file

Or, use awk:

awk -F';' '{$2 = "@"$2}1' OFS=';' file

All the above commands result in the same output for your example file:

aaa;@111;bbb
ccc;@222;ddd
eee;@333;fff
Sign up to request clarification or add additional context in comments.

3 Comments

OP only wants on the second column. This will change it, throughout the file
He wants the second column, which is the first ;. See the desired output in his question. I would love to see the awk solution from you.
Yes, tested all three solutions in my answer. Do you see any issues?
1

@atb: Try: 1st:

awk -F";" '{print $1 FS "@" $2 FS $3}'  Input_file

Above will work only when your Input_file has 3 fields only.

2nd:

awk -F";" -vfield=2 '{$field="@"$field} 1' OFS=";"   Input_file

Above code you could put any field number and could make it as per your request. Here I am making field separator as ";" and then taking a variable named field which will have the field number in it and then that concatenating "@" in it's value and 1 is for making condition TRUE and not making and action so by default print action will happen of current line.

Comments

1

You just misunderstood how to set variables. Change -OFS to -v OFS:

awk -F';' -v OFS=';' '{ $2 = "@" $2 }1' file

but in reality you should set them both to the same value at one time:

awk 'BEGIN{FS=OFS=";"} { $2 = "@" $2 }1' file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.