选择文本文件的特定字段范围

选择文本文件的特定字段范围

我有一个文本文件文件nr.lis, 其中包含

#  1  2016-05-31-1003-57S._BKSR_003_CM6
#  2  2016-06-01-2255-54S._BKSR_003_CM6
#  3  2016-06-05-1624-57S._BKSR_003_CM6
#  4  2016-06-07-1914-55S._BKSR_003_CM6
.
.
.

等等。

我的输出应该是这样的

2016-05-31-10-03
2016-06-01-22-55
2016-06-01-22-55
2016-06-07-19-14

我已经尝试过,但它没有相应的格式:

awk -F'-' '{print "2016""-"$2"-"$3"-"$4}' filenr.lis

答案1

awk

awk '{print substr($3,0,13)"-"substr($3,14,2)}' file.txt
2016-05-31-10-03
2016-06-01-22-55
2016-06-05-16-24
2016-06-07-19-14

sed

sed 's/^......\(.............\)\(..\).*/\1-\2/' file.txt

sed,但更聪明一点

sed 's/^.\{6\}\(.\{13\}\)\(..\).*/\1-\2/' file.txt

珀尔

perl -pe 's/^.{6}(.{13})(..).*/$1-$2/' file.txt

答案2

基于固定列-固定大小-固定字符位置的剪切方案:

$ cut --output-delimiter='-' -c7-19,20-21 file.txt
# display from char 7 up to 19, then print output delimiter, then display from char 20 up to char 21.

重击解决方案:

$ while IFS= read -r line;do line="${line:6:13}-${line:14:2}";echo $line;done<file.txt

基于字段而不是字符的解决方案:

while IFS= read -r line;do 
  line=$(cut -d' ' -f5- <<<"$line") #with space delimiter get field 5 up to the end
  line=$(cut -d- -f1-4 <<<"$line") #with delimiter="-" get field 1 up to 4
  line=$(sed "s/${line: -2}/-${line: -2}/g" <<<"$line") #insert a dash before last two characters
  echo "$line"
done<file

作为具有流程替换的单行代码:

$ sed 's/..$/-\0/g' <(cut -d- -f1-4 <(cut -d" " -f5- file.txt)) #use >newfile at the end to send the results to a new file

# 1在所有情况下,考虑到您的输入文件(并包括每行的开头),结果都符合预期

答案3

我个人最喜欢 awk 解决方案,但这是另一种方法

cat FILE_NAME | tr -s ' ' | cut -d' ' -f3 | cut -b 1-13

相关内容