简体   繁体   中英

How do I add a new column with a specific word to a file in linux?

I have a file with one column containing 2059 ID numbers.
I want to add a second column with the word 'pop1' for all the 2059 ID numbers.
The second column will just mean that the ID number belongs to population 1.

How can I do this is linux using awk or sed?

The file currently has one column which looks like this

45958 
480585 
308494

I want it to look like:

45958 pop1
480585 pop1
308494 pop1

Maybe not the most elegant solution, and it doesn't use sed or awk, but I would do that:

while read -r line; do echo ""$line" pop1" >> newfile; done < test

This command will append stuff in the file 'newfile', so be sure that it's empty or it doesn't exist before executing the command.

Here is the resource I used, on reading a file line by line: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/

A Perl solution.

$ perl -lpi -e '$_ .= " pop1"' your-file-name

Command line options:

  • -l: remove newline from input and replace it on output
  • -p: put each line of input into $_ and print $_ at the end of each iteration
  • -i: in-place editing (overwrite the input file)
  • -e: run this code for each line of the input

The code ( $_.= " pop1" ) just appends your string to the input record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM