How to store part of the file name into a variable using shell script? [duplicate] - linux

This question already has answers here:
How do I set a variable to the output of a command in Bash?
(15 answers)
How do I remove the file suffix and path portion from a path string in Bash?
(15 answers)
Closed 1 year ago.
I have a file 20210823_Club_Member_Name_by_ID.txt. I want to get only the first element of the file name which is 20210823 and store it into a variable using shell script.
Currently, my code can print out the first element in the terminal but I also want to store it into a variable for further usage.
file='20210823_Club_Member_Name_by_ID.txt'
echo "$file" | awk -F'[_.]' '{print $1}'
// I try to store it like below, but it does not work
fileDate= echo "$file" | awk -F'[_.]' '{print $1}'
echo $fileDate

As Jetchisel commented, you can use shell parameter expansion to safely extract the value. The %% operator removes as much of the matching text as possible, starting from the end of the string; if we use _* then this will essentially remove everything after and including the first underscore.
file='20210823_Club_Member_Name_by_ID.txt'
fileDate="${file%%_*}"
The fileDate variable will now contain 20210823.

Related

Using sed to replace a pattern matched with an exported variable [duplicate]

This question already has answers here:
Using variables in sed -f (where sed script is in a file rather than inline)
(5 answers)
Closed 3 years ago.
How can I use sed to replace the matched pattern with EXPORT variable? Or is there a way I can access shell script variables when invoking sed file?
shell_cript.sh
for i in ./data/*.sav;
do
read_input (){
read number_one number_two
read date1 inventory
read price
} < $i
read_input
export number_one
export i
export number_two
export inventory
export price
sed -f test.sed $2
done
test.sed
s/Filename/$i/g
s/1stplace/$number_one/g
s/2ndplace/$number_two/g
s/\$\$\$\$/$price/g
file.sav
Jonathan Lee
12/12/2019 2
1000
If you put all your sed commands in a sed script file, you will not be able to pass variables to it.
What you need to do is pass all your sed commands at the command line level and use double quotes " to have your bash/shell interpret the $ and do the proper variable substitutions. You do not need to export the variables as the variable substitution will be done by the shell before creating your sed subprocess.
sed 's/Filename/'"$i"'/g;s/1stplace/number_one/g;s/2ndplace/number_two/g;s/\$\$\$\$/price/g'

How to extract a value of a key from a long string with sed? [duplicate]

This question already has answers here:
Can I use sed to manipulate a variable in bash?
(3 answers)
Closed 4 years ago.
I have a long string and from that string I want to extract a value of a key and store it in a variable. I want to extract value of userName from abc string. I tried below code but it say's file name too long error.
abc="Create [newSystem=System [identityDomain=bbundlesystemser201201-test, admin=AdminUser [firstName=BSystemAdminGivenName, middleName=null, lastName=BSystemAdminFalilyName, userName=bbundlesystemadminusername, password=*******, email=hello#example.com], idmConsoleURL=https://abc.com.jspx, sftpHost=d910.abc.com, sftpUser=3pyylzoo, sftpPwd=*******]]"
echo $abc
sed -n 's/^userName= //p' "$abc"
Is there anything wrong I am doing? I want to extract value of userName and store it in a variable.
userName=bbundlesystemadminusername
You can use BASH regex matching:
[[ $abc =~ userName=([^][,[:space:]]+) ]] && userName="${BASH_REMATCH[1]}"
echo "$userName"
bbundlesystemadminusername
Or else, you can use this sed command:
userName=$(sed 's/.*userName=\([^][,[:space:]]*\).*/\1/' <<< "$abc")
I think I'd do this with an associative array and process substitution in bash 4:
$ declare -A a
$ while IFS== read k v; do a["$k"]="$v"; done < <(grep -oEi '[a-z]+=[^], ]+' <<<"$abc")
$ printf '%q\n' "${a[userName]}"
bbundlesystemadminusername
While this doesn't properly respect the data structure of your input variable, it does recognize key=value pairs and save them in an easily accessible array, using only a single grep -o to split the string into the KV pairs. The nice this about this is of course that you've got the rest of the data also available to you, should you want to avoid unnecessary calls to grep or awk or sed or whatever.
Note that associative arrays were added to bash in version 4. If you're doing this in macOS (or indeed in a POSIX shell), it'll have to be adjusted.

"Command not found" piping a variable to cut when output stored in a variable [duplicate]

This question already has answers here:
How to pass the value of a variable to the standard input of a command?
(9 answers)
Closed 5 years ago.
In a bash script I am using a variable to hold a path like this:
MY_DIR=/just/a/string/to/my/path
And I want to remove the last two parts of it so it looks like this:
/just/a/string
I am using 'cut' to do it, like this:
echo $MY_DIR | cut -d'/' -f-4
The output is what I expect. Fine.
But I want to store in an other variable, like this:
MY_DIR2=$($MY_DIR | cut -d'/' -f-4)
When I execute the script I get the error:
... /just/a/string/to/my/path: No such file or directory
Why is the direct output with echo working, but storing the output in a variable is not?
You need to pass an input string to the shell command using a pipeline in which case cut or any standard shell commands, reads from stdin and acts on it. Some of the ways you can do this are use a pipe-line
dir2=$(echo "$MY_DIR" | cut -d'/' -f-4)
(or) use a here-string which is a shell built-in instead of launching a external shell process
dir2=$(cut -d'/' -f-4 <<< "$MY_DIR")
Use the grave accent(`) to emulate a command, and use echo too.
MY_DIR2=`echo $MY_DIR | cut -d'/' -f-4`

Read first characters of a variable in bash script? [duplicate]

This question already has answers here:
In Bash, how can I check if a string begins with some value?
(13 answers)
Closed 6 years ago.
I have a file where i get some informations through a bash script to put data in a DB table and i'd like to know how to read the first characters of a variable because if it starts with "CE-" that line's data will go into a table if not they must be inserted in an other one, how can i do this?
Like this-
var=CE-xxxxx
echo "$var"
output- CE-xxxxx
var2=$(echo "$var" | cut -c 1-3)
echo "$var2"
output- CE-
Then you can check if $var2 matches your criteria and use it further.
You can use cut to get the bytes that you need:
V="CE-IMPORTANT"
I=$(echo $V | cut -b 4-)
If you want to use the - as separator:
I=$(echo $V | cut -d '-' -f 2)
In both cases you get "IMPORTANT" in I var

How to delete last found value in Bash [duplicate]

This question already has answers here:
Bash : extracting part of a string
(4 answers)
Closed 6 years ago.
Say I have a string 0.0.25, how do I delete the last part after dot (including it) to make it like 0.0? Note that last part can have variable number of digits.
In bash you can do the following:
echo "${var%.*}"
See the Shell Parameter Expansion section of the manual.
Using awk you could:
echo "0.0.25" | awk -F. '{print $1"."$2}'

Resources