如何使用linux限制行中存在的字符串长度

时间:2013-11-08 22:16:09

标签: linux bash ubuntu

我有以下表格的数据:

num1    This is a string
num2    This is another string

我想限制在第一个标签之后的所有字符串的长度。这样长度(字符串)<4。因此,我得到的输出是:

num1    This is a string
num2    This is another 

我可以使用python来做到这一点。但我试图找到一个等价的Linux来实现同样的目标。

3 个答案:

答案 0 :(得分:20)

在bash中,您可以使用以下命令限制字符串,在本例中,从索引0到索引17。

$ var="this is a another string"

$ echo ${var:0:17}

this is a another

答案 1 :(得分:13)

使用,按列:

$ awk '{print $1, $2, $3, $4}' file

sed -r 's@^(\S+\s+\S+\s+\S+\s+\S+).*@\1@' file

或使用的长度:

$ cut -c 1-23 file

答案 2 :(得分:0)

如果您要截断字边界上的字符串,可以将fold与-s选项一起使用:

awk -F"\t" '{
    printf "%s\t", $1; system(sprintf("fold -sw 17 <<< \"%s\" | sed q", $2))
}'

缺点是fold并且需要为每一行调用sedsed qtail -n1相同)。