Pablo
Pablo

Reputation: 515

Extra "-" at the end of the line

I have a .txt file which consists of multiple lines. Some of these lines start with numbers. I want to find these lines and merge them into one line and write the output to another .txt file.

Hello
I'm fine
1first
2second
ok

I want the result to be like this: 1first-2last

Therefore I use this code:

grep '^[0-9]' first.txt | tr '\n' '-' > last.txt

In which \n in replaced with -, but since there are other lines after the lines starting with numbers, when I open my output file, there is a - at the end of the generated line. I mean the last \n is also replaced with - and the result is like this:

1first-2last-

How can I avoid this? I don't want - at the of my line.

Upvotes: 0

Views: 47

Answers (3)

chepner
chepner

Reputation: 531075

Use ed:

printf '%s\n' 'v/^[0-9]/d' '1,$-1s/$/-/' '%j' 'wq last.txt' | ed first.txt

This will remove all lines that don't start with a number, the add a - to every line but the last, then join them, then write the result to last.txt (not back to first.txt, before quitting without saving the changes to first.txt.

$ cat first.txt
Hello
I'm fine
1first
2second
ok
$ printf '%s\n' 'v/^[0-9]/d' '1,$-1s/$/-/' '%j' 'wq last.txt' | ed first.txt
33
?
$ cat last.txt
1first-2second
$ cat first.txt
Hello
I'm fine
1first
2second
ok

ed just reads commands from standard input, so you can use a here document if you prefer:

ed first.txt <<'EOF'
v/^[0-9]/d
1,$-1s/$/-/
%j
wq last.txt
EOF

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 140970

You could replace last - with a newline.

grep '^[0-9]' first.txt | tr '\n' '-' | sed 's/-$/\n/'

or with nothing:

grep '^[0-9]' first.txt | tr '\n' '-' | sed 's/-$//'

But if you want to join the lines with - as separator you want:

grep '^[0-9]' first.txt | paste -sd'-' -

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295373

If your file is short enough that bash's built-in string handling is adequate, this can be as simple as:

readarray -t lines <first.txt
IFS=-
printf '%s\n' "$*" >second.txt

Upvotes: 1

Related Questions