Reputation: 21
I have a document resembling this format (with many more lines):
abc
def
hij
klm
nop
I need the output file to look like this:
>1
abc
>2
def
>3
hij
>4
klm
>5
nop
Basically, inserting a header with a number count before the start of each existing line. I've been experimenting using the sed command but so far without any success. Can anybody offer a suggestion on how to achieve this using Bash?
Upvotes: 0
Views: 52
Reputation: 37464
Using nl
, number lines of files:
$ nl -s $'\n' -w 1 file
1
abc
2
def
3
hij
4
klm
5
nop
man nl
:
-s, --number-separator=STRING
add STRING after (possible) line number
-w, --number-width=NUMBER
use NUMBER columns for line numbers
Upvotes: 0
Reputation: 3183
A solution with awk
$ awk '{print ">"NR "\n"$0}' 1.txt
>1
abc
>2
def
>3
hij
>4
klm
>5
nop
Upvotes: 2
Reputation: 684
Simple and readable solution: Iterate, increment, output.
Storing output in a file called output.txt
:
header=1 #Header is num to insert
for item in `cat lines.txt`; #loop through your other file
do
echo $header >> output.txt #Insert header
echo $item >> output.txt #Insert line from file
header=$((header+1)) #Increment the header
done
Gives you an output that looks like:
$cat output.txt
1
egg
2
steak
3
cheese
4
chicken
5
asparagus
Still Simple, slightly less readable solution:
header=1
for item in `cat lines.txt`;
do
echo -e "$header\n$item" >> output.txt #Use echo -e to interpret newline character.
header=$((header+1))
done
Gives the same output:
$cat output.txt
1
egg
2
steak
3
cheese
4
chicken
5
asparagus
Upvotes: 0