How to remove \n between the outputs of two echo commands?
Don't do this sort of thing in the shell! It is far more complex than necessary, prone to errors and far, far, slower. There are many tools designed for such text manipulation. For example, in sed
(here assuming recent GNU or BSD implementations for -E
):
$ sed -E 's/([^_]*).*/& \1/' file
111_c4l5r120.png 111
123_c4l4r60.png 123
135_c4l4r180.png 135
147_c4l3r60.png 147
15_c4l1r120.png 15
Or, for any sed
:
$ sed 's/\([^_]*\).*/& \1/' file
111_c4l5r120.png 111
123_c4l4r60.png 123
135_c4l4r180.png 135
147_c4l3r60.png 147
15_c4l1r120.png 15
Perl:
$ perl -pe 's/(.+?)_.*/$& $1/' file
111_c4l5r120.png 111
123_c4l4r60.png 123
135_c4l4r180.png 135
147_c4l3r60.png 147
15_c4l1r120.png 15
awk:
$ awk -F_ '{print $0,$1}' file
111_c4l5r120.png 111
123_c4l4r60.png 123
135_c4l4r180.png 135
147_c4l3r60.png 147
15_c4l1r120.png 15
Unless you have a specific need to use the shell for this, terdon's answer provides better alternatives.
Since you're using bash
(as indicated in the script's shebang), you can use the -n
option to echo:
echo -n "${line} " >> output.txt
echo "$line" | cut -d'_' -f 1 >> output.txt
Or you can use shell features to process the line without using cut
:
echo "${line} ${line%%_*}" >> output.txt
(replacing both echo
lines).
Alternatively, printf
would do the trick too, works in any POSIX shell, and is generally better (see Why is printf better than echo? for details):
printf "%s " "${line}" >> output.txt
echo "$line" | cut -d'_' -f 1 >> output.txt
or
printf "%s %s\n" "${line}" "${line%%_*}" >> output.txt
(Strictly speaking, in plain /bin/sh
, echo -n
isn't portable. Since you're explicitly using bash
it's OK here.)
Here you are:
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
echo "$line" `echo "$line" | cut -d'_' -f 1` >> output.txt
# echo "$line" | cut -d'_' -f 1 >> output.txt
done < "$1"
Output:
$ rm -rf output.txt
$ ./test.sh 1.1; cat output.txt
111_c4l5r120.png 111
123_c4l4r60.png 123
135_c4l4r180.png 135
147_c4l3r60.png 147
15_c4l1r120.png 15