TransWikia.com

Select the particular range of of fields of a text file

Unix & Linux Asked by Preet on January 5, 2021

I have a text file filenr.lis, which contains

#  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
.
.
.

and so on.

And my output should be like

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

I have tried this, but it has not formatted accordingly:

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

3 Answers

I personally like the awk solution the best, but here's another way

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

Answered by dedricF on January 5, 2021

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, but a little smarter

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

perl

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

Answered by steve on January 5, 2021

Cut solution based on fixed columns - fixed size - fixed character position:

$ 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.

Bash Solution:

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

Solution based on fields and not characters:

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

As one-liner with process substitution:

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

In all cases the result is as expected, considering your input file (and including # 1 in the beginning of each line)

Answered by George Vasiliou on January 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP