Reputation: 5
I am new to using the Mac terminal. I need to add a tab delimited column to a text file with 3 existing columns. The columns look pretty much like this:
org1 1-20 1-40
org2 3-35 6-68
org3 16-38 40-16
etc.
I need them to look like this:
org1 1-20 1-40 1
org2 3-35 6-68 2
org3 16-38 40-16 3
etc.
My apologies if this question has been covered. Answers to similar questions are sometimes exceedingly esoteric and are not easily translatable to this specific situation.
Upvotes: 0
Views: 335
Reputation: 21502
If you want to add the line numbers to the last column:
perl -i -npe 's/$/"\t$."/e' file
where
-i
replaces the file in-pace (remove, if you want to print the result to the standard output);-n
causes Perl to apply the substitution to each line from the file, just like sed;-p
prints the result of expression;-e
accepts Perl expression;s/.../.../e
substitutes the first part to the second (delimited with slash), and the e
flag causes Perl to evaluate the replacement as Perl expression;$
is the end-of-line anchor;$.
variable keeps the number of the current line In other words, the command replaces the end of the line ($
) with a tab followed by the line number $.
.
Upvotes: 1
Reputation: 52211
You can paste the file next to the same file with line numbers prepended (nl
), and all the other columns removed (cut -f 1
):
$ paste infile <(nl infile | cut -f 1)
org1 1-20 1-40 1
org2 3-35 6-68 2
org3 16-38 40-16 3
The <(...)
construct is called process substitution and basically allows you to treat the output of a command like a file.
Upvotes: 0
Reputation: 37414
In awk. print
the record and the required tab and row count after it:
$ awk '{print $0 "\t" NR }' foo
org1 1-20 1-40 1
org2 3-35 6-68 2
org3 16-38 40-16 3
Upvotes: 4