Using vi, awk, sed - erase / remove / cut Few First , Last Characters in all lines of Linux file

advertisements

_____________________________________________________________________________________________________________________

The Eucharistic Miracles of the World

I have a text file called dat.txt and it having some generic text characters in the first and last of every line. I wanted to remove these charcters. See different options by using vi, awk, sed.


Content of my input dat.txt file is
$ cat dat.txt

xml.1-CCJGL1-CCJGL1-CCJGL.rec
xml.1-BSDF0Q1-BW;LKJ1-BWP30Q.rec
xml.1-LKJ<MN1-1LKJMG1-1W13LG.rec
xml.1-2<MBMV1-NVNBVKJH21HMRE.rec
xml.1-2EW*&Y1-(878761-2AJKGY.rec

Using vi editor:
Open the file in vi and run following commands.
  1. To remove 4 characters from the beginning of every lines of a file

:%s/^....//g

  1. To remove 4 characters from the end of every lines of a file

:%s/....$//g
Using sed
  1. Remove 4 characters from the beginning of every lines

$ sed -r "s/^(.{0})(.{4})//" dat.txt

1-CCJGL1-CCJGL1-CCJGL.rec
1-BSDF0Q1-BW;LKJ1-BWP30Q.rec
1-LKJ<MN1-1LKJMG1-1W13LG.rec
1-2<MBMV1-NVNBVKJH21HMRE.rec
1-2EW*&Y1-(878761-2AJKGY.rec

  1. To remove 4 characters from the end of every lines of a file

$ sed -r "s/(.{0})(.{4})$//" dat.txt

xml.1-CCJGL1-CCJGL1-CCJGL
xml.1-BSDF0Q1-BW;LKJ1-BWP30Q
xml.1-LKJ<MN1-1LKJMG1-1W13LG
xml.1-2<MBMV1-NVNBVKJH21HMRE
xml.1-2EW*&Y1-(878761-2AJKGY

Using awk

  1. Remove 4 characters from the beginning of every lines

$ awk 'sub("^....", "")' dat.txt

1-CCJGL1-CCJGL1-CCJGL.rec
1-BSDF0Q1-BW;LKJ1-BWP30Q.rec
1-LKJ<MN1-1LKJMG1-1W13LG.rec
1-2<MBMV1-NVNBVKJH21HMRE.rec
1-2EW*&Y1-(878761-2AJKGY.rec

  1. Remove 4 characters from the end of every lines

$ awk 'sub("....$", "")' dat.txt

xml.1-CCJGL1-CCJGL1-CCJGL
xml.1-BSDF0Q1-BW;LKJ1-BWP30Q
xml.1-LKJ<MN1-1LKJMG1-1W13LG
xml.1-2<MBMV1-NVNBVKJH21HMRE
xml.1-2EW*&Y1-(878761-2AJKGY

Using Shell Script

  1. Remove 4 characters from the beginning of every lines

$ while read LINE
do
      echo "$LINE"|cut -c5-
done < dat.txt

$ while read LINE
do
      echo ${LINE:4}
done < dat.txt

  1. Remove 4 characters from the end of every lines

$ while read LINE
do
      echo "${LINE%????}"
done < dat.txt

_____________________________________________________________________________________________________________________

Website Stats

0 comments:

Post a Comment

Labels

Oracle (629) Script (86) General (77) Unix (47) Blog (23) Technology (19) gadget (6) games (6) Business (3) OCI (3) SQL* Loader (3) Datapump (2)
 

acehints.com Copyright 2011-23 All Rights Reserved | Site Map | Contact | Disclaimer