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条回答
男人必须洒脱
2楼-- · 2019-07-25 13:47

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
查看更多
登录 后发表回答