Unwanted line break using echo and cat

2019-03-01 18:11发布

I'm trying to add a line at the beginning of a file, using

echo 'time/F:x1:x2' | cat - file.txt>newfile.txt

But this produces line breaks at each line in the new file (except for after the added 'time/F:x1:x2' line). Any ideas on how to avoid this?

3条回答
做个烂人
2楼-- · 2019-03-01 18:26

Use -n to disable the trailing newline:

echo -n 'time/F:x1:x2' | cat - file.txt > newfile.txt

There are other ways, too:

sed '1s|^|time/F:x1:x2|' file.txt > newfile.txt
查看更多
聊天终结者
3楼-- · 2019-03-01 18:37

How about

{ echo 'time/F:x1:x2'; cat file.txt; } >newfile.txt

or

sed '1i\
time/F:x1:x2' file.txt > newfile.txt
查看更多
看我几分像从前
4楼-- · 2019-03-01 18:44

Actually you don't even need the echo and pipe if you're using bash. Just use a herestring:

<<< 'time/F:x1:x2' cat - file.txt > newfile.txt
查看更多
登录 后发表回答