Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed to insert characters in a specific column

Tags:

sed

awk

Can anyone tell me how to insert chr to every character in the first column.

file in

1 34566 34765    
2 45678 45789
3 34567 34799
X 67895 66900
Y 34567 34890

file out

chr1 34566 34765
chr2 45678 45789
chr3 34567 34799
chrX 67895 66900
chrY 34567 34890

I can't figure out how to make sed -i apply to a specific column. I'm not good with the syntax so if you could break down your explanation I would be grateful. Also, would it be better to use awk for this?

like image 238
user2929841 Avatar asked Oct 28 '13 22:10

user2929841


People also ask

How do you use sed on a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.

What is I flag in sed?

In sed , you can end a command with the flag "/i" (for example, see this other question). This seems to say "more sed commands coming," or something like that, so you can split sed commands in a script.

What is E option in sed?

sed -e '1,10d' The -e tells sed to execute the next command line argument as sed program. Since sed programs often contain regular expressions, they will often contain characters that your shell interprets, so you should get used to put all sed programs in single quotes so your shell won't interpret the sed program.

How do you insert a sed line after a pattern?

You have to use the “-i” option with the “sed” command to insert the new line permanently in the file if the matching pattern exists in the file.


2 Answers

With sed:

sed 's/^/chr/' file.in > file.out

You don't need the -i-flag because you aren't overwriting the input-file file.in.

With awk:

awk '{print "chr"$0}' file.in > file.out
like image 108
EverythingRightPlace Avatar answered Nov 12 '22 01:11

EverythingRightPlace


sed 's|^|chr|' file_in > file_out

This does a substitution (s) at the beginning of each line (^) and replacing it with the characters "chr". The pipes (|) are just separators.

like image 40
Quetza Avatar answered Nov 12 '22 02:11

Quetza