Tuesday, November 2, 2021

[SOLVED] Shell script to select particular letters in a word and print that word ignoring other letters in linux

Issue

I want a script to select letters between a word and print that word ignoring other letters in multiple files.

I have file with same name but the middle name is different so I want to select that word and list it.

I have

backup-aniketn-05-34-23-Fri-Sep-2019.tar.gz
backup-checkte-05-38-18-Fri-Sep-2019.tar.gz
backup-aniketi-06-03-11-Fri-Sep-2019.tar.gz
backup-aniketi01-10-45-31-Sat-Sep-2019.tar.gz

I want to select names between the 2 hyphens and list ignoring rest of the words

aniketn 
checkte 
aniketi 
aniketi01

I'm trying to get this output. I tried using cut command but didn't helped searching for a script Please Help.

Thank You!


Solution

You can simply use below two commands to fetch the second element from name :

cut -d- -f2
awk -F'-' '{print $2}'

In cut command -d is for selecting delimiter and -f2 will print the second word.

In awk command -F is for selecting delimiter and print $2 will print second word.



Answered By - Pacifist