Search code examples
bashshellunixscriptingksh

how to extract a part of file name in unix scripting and check if it exists


I need to write a script where I have to extract part of the name from a file abc_def_xxx_yyy_20210515.txt and check if abc_def_xxx_yyy.txt exists. If not then create the file.

FILE="abc_def_xxx_yyy_20210515.txt"
DLS=echo $FILE | awk -F_ '{print $1,$2,$3,$4".txt"}'
DLL=\home\xxx\$DLS
if [-f "$DLL"]; then
echo "$DLL exists"
else 
touch "$DLL"
fi

I get the error saying "abc_def_xxx_yyy_20210515.txt" not found

but if I just run with

FILE="abc_def_xxx_yyy_20210515.txt"
echo $FILE | awk -F_ '{print $1,$2,$3,$4".txt"}' 

I get abc_def_xxx_yyy.txt.

Can someone please help me with this?


Solution

  • Try:

    FILE="abc_def_xxx_yyy_20210515.txt"
    DLS="${FILE%_*}.txt"
    DLL="$HOME/$DLS"
    if [ -f "$DLL"]; then
      echo "$DLL exists"
    else 
      touch "$DLL"
    fi