如何在不丢失其他字段的情况下缩短文本的中间字段

How to shorted the middle field of text without losing the other fields

抱歉,如果这已经涵盖了。我找不到合适的东西。

如果我有一个包含可变长度字段的文本文件,如何在不牺牲其他字段的情况下截断一个字段?一个例子;

firstField secondfieldisthislong thirdField
firstField secondfieldisreallylongandgoesonforever thirdField
firstField secondshortfield thirdField

我想将第二个字段截断为固定长度。 cut 好像做不到,而且我的 awk/sed 技术也不是很好。谢谢

awk:

awk '{ = substr(, 1, 10)}; 1' file.txt

10替换成你想要的字符长度。

这里我们正在重建记录,第二个字段被截断到所需的长度。

substr(, offset, length) 将进行字符串切片,从 offsetlength 个字符。

示例:

% cat file.txt                              
firstField secondfieldisthislong thirdField
firstField secondfieldisreallylongandgoesonforever thirdField
firstField secondshortfield thirdField

% awk '{ = substr(, 1, 6)}; 1' file.txt
firstField second thirdField
firstField second thirdField
firstField second thirdField

% awk '{ = substr(, 1, 10)}; 1' file.txt
firstField secondfiel thirdField
firstField secondfiel thirdField
firstField secondshor thirdField

使用 GNU sed:

$ sed -r 's/(.* .{6}).* / /' <<< "firstField secondfieldisreallylongandgoesonforever thirdField"
firstField second thirdField