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
Related
This question already has answers here:
Conditional step in a pipeline
(2 answers)
Can I make a shell function in as a pipeline conditionally "disappear", without using cat?
(1 answer)
Closed 4 months ago.
EMPTY_VAR=''
MMDDYYYY='6.18.1997'
PIPE_VAR=' | xargs echo "1+" | bc'
echo "$MMDDYYYY" | cut -d "." -f 2${EMPTY_VAR}
>> 18
Command above would give me correct output, which is 18, but if I try to use PIPE_VAR instead it would give me bunch of errors:
echo "$MMDDYYYY" | cut -d "." -f 2${PIPE_VAR}
cut: '|': No such file or directory
cut: xargs: No such file or directory
cut: echo: No such file or directory
cut: '"1+"': No such file or directory
cut: '|': No such file or directory
cut: bc: No such file or directory
OR:
echo "$MMDDYYYY" | cut -d "." -f 2"$PIPE_VAR"
cut: invalid field value ‘| xargs echo "1+" | bc’
Try 'cut --help' for more information.
What I'm really trying to find out is that even possible to combine commands like this?
You can't put control operators like | in a variable, at least not without resorting to something like eval. Syntax parsing comes before parameter expansion when evaluating the command line, so Bash is only ever going to see that | as a literal character and not pipeline syntax. See BashParsing for more details.
Conditionally adding a pipeline is hard to do well, but having a part of the pipeline conditionally execute one command or another is more straightforward. It might look something like this:
#!/bin/bash
MMDDYYYY='6.18.1997'
echo "$MMDDYYYY" | cut -d "." -f 2 |
if some_conditional_command ; then
xargs echo "1+" | bc
else
cat
fi
It looks like you're trying to calculate the next day. That's hard to do with plain arithmetic, particularly with month/year ends.
Let date do the work. This is GNU date. It can't parse 6.18.1997 but it can parse 6/18/1997
for MMDDYYYY in '2.28.1996' '2.28.1997'; do
date_with_slashes=${MMDDYYYY//./\/}
next_day=$(date -d "$date_with_slashes + 1 day" '+%-m.%-d.%Y')
echo "$next_day"
done
2.29.1996
3.1.1997
This question already has answers here:
How to replace one character with two characters using tr
(5 answers)
Closed 3 years ago.
Hi I have a shell script that has
variable="apple banana monkey"
I want it to be
apple\nbanana\nmonkey
But when I try and execute
echo $variable | tr ' ' '\n'
It results to
apple
banana
monkey
I want to get the actual literal of new line and not the evaluated value.
I have tried echo -e or echo -n or even put numerous escapes \\ but to no avail.
Please help. Thanks
tr command translates chars into chars by performing a 1 to 1 mapping. You are asking the tool to translate a space into two chars, which is something that cannot be done with tr.
If you accept a command switch, you can try with sed:
echo "$variable" | sed 's/ /\\n/g'
This question already has answers here:
A variable modified inside a while loop is not remembered
(8 answers)
Closed 3 years ago.
I have s simple bash script as follow:
interval=""
cat conf.param|\
while read param
do
item_=$(echo $param|cut -d "=" -f1)
case ${item_} in
interval)
interval=$(echo $param|cut -d "=" -f2)
echo $interval
;;
method)
method=$(echo $param|cut -d "=" -f2)
;;
esac
done
echo "${interval}"
It reads the contents of a file and stores them in different variables. the issue is that the variables are not set properly inside case segment. I put two echos. The first one (inside case) displays the interval value correctly which is '2', but the second one just after the esac statement displays nothing! it shows an empty blank line.
the conf.param is a simple text file. it has more lines I only printed two lines:
interval=2
method="POST"
Your problem is that using a pipe ("cat conf.param | while read param"), you call a second shell which can not export its variables to the calling one. See this example:
interval=""
cat tmp.txt | while read param; do ##### DON'T DO THIS
interval="A$interval"
done
echo "First attempt: $interval"
interval=""
while read param; do
interval="A$interval"
done < tmp.txt ##### BUT DO THIS INSTEAD
echo "Redirection attempt: $interval"
The file tmp.txt contains 4 lines; the output of the script is:
First attempt:
Redirection attempt: AAAA
As you see, the first attempt retains the old value of interval. The second/redirection attempt instead works because no new process is created.
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.
This question already has an answer here:
how to print certain column with numbers only in awk
(1 answer)
Closed 5 years ago.
i am writing a bash script, and when i execute a certain command from my script it spits out an ID like this
VM ID: 12345
IDs are different all the time. How would I be able to extract just the number of ID and store it in my script?
I tried to put a ">file" after the command and it does not seem to work.
So, it depends on the possible IDs.
If it is always the 3rd item in string.
echo "VM ID: 12345" | awk '{print $3}' > file
If the output is always the only numbers in the output you can use tr.
echo "VM ID: 12345" | tr -d '[:alpha:][:blank:][:punct:]'
12345
However, if another number is in the string it will be added.
echo "VM3 ID: 12345" | tr -d '[:alpha:][:blank:][:punct:]'
312345
You can also make a pattern that gets the number after the first ":"