4

I want to replace new lines in text with coma or space but do not change the last new line.

I know of this question: How to replace newlines with tab characters? - but it does produce an tab on end instead of new line.

So far I have come with:

awk 'NR>1{printf","} {printf $1} END{printf"\n"}'

Is there an easier way to do this? This is not an assignment, I am just curious want to level up my scripting.

Community
  • 1
  • 1
mpapis
  • 52,729
  • 14
  • 121
  • 158

4 Answers4

14

This might work for you:

paste -s -d, file

or

paste -s -d" " file
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
potong
  • 55,640
  • 6
  • 51
  • 83
3

This should do a job:

echo  ${$(tr '\n' ',' < file)%?}

or perhaps using sed:

sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/,/g' file
Netf
  • 141
  • 3
  • I was searching for something less magical, those both require quite good knowledge of `bash`/`tr` or `sed` respectively – mpapis Aug 04 '13 at 12:39
1

Using perl is not quite as simple as paste, but it does generalize to more cases:

perl -0pe 's/\n(?!$)/,/g' filename  # comma
perl -0pe 's/\n(?!$)/ /g' filename  # space

The (?!$) is a lookahead assertion that means "not at the end", so the last newline is left alone.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
0

You can use sed command to remove the end ","

 # sed -i 's/,$//g' endmodify.txt

 # cat endmodify.txt
 root
 bin
 daemon
 adm
 lp
 sync
 games
 gopher

Thanks.

Ranjithkumar T
  • 1,886
  • 16
  • 21