如何删除最后一个字符CR用`cut`(How to remove the last CR char

2019-09-26 20:03发布

我想获得使用字符串的一部分cut 。 这里的虚拟实例:

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

注意\n在结束时加入炭。

在这种情况下,没有一点用cut删除最后一个字符如下:

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

我仍然会得到这额外和不必要的字符,我想避免使用额外的命令,例如:

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

Answer 1:

\n是通过添加echo 。 相反,使用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

很有趣的是cut本身还增加了一个新行:

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

因此,解决方案似乎使用printf它的输出:

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


文章来源: How to remove the last CR char with `cut`