How to remove the last CR char with `cut`

2019-07-25 13:32发布

问题:

I would like to get a portion of a string using cut. Here a dummy example:

$ echo "foobar" | cut -c1-3 | hexdump -C
00000000  66 6f 6f 0a                                       |foo.|
00000004

Notice the \n char added at the end.

In that case there is no point to use cut to remove the last char as follow:

echo "foobar" | cut -c1-3 | rev | cut -c 1- | rev

I will still get this extra and unwanted char and I would like to avoid using an extra command such as:

shasum file | cut -c1-16 | perl -pe chomp

回答1:

The \n is added by echo. Instead, use printf:

$ echo "foobar" | od -c
0000000   f   o   o   b   a   r  \n
0000007
$ printf "foobar" | od -c
0000000   f   o   o   b   a   r
0000006

It is funny that cut itself also adds a new line:

$ printf "foobar" | cut -b1-3 | od -c
0000000   f   o   o  \n
0000004

So the solution seems using printf to its output:

$ printf "%s" $(cut -b1-3  <<< "foobar") | od -c
0000000   f   o   o
0000003