Output exactly x number of characters to variable using read in Bash [duplicate] - string

This question already has answers here:
Extract substring in Bash
(26 answers)
Closed 6 years ago.
How to retrieve the first 10 characters of a variable with Bash?
FOO="qwertzuiopasdfghjklyxcvbnm"
I need to get qwertzuiop.

If the variable is: FOO="qwertzuiopasdfghjklyxcvbnm"
then
echo ${FOO:0:10}
will give the first 10 characters.

Use the head command.
echo $FOO | head -c 10
=> qwertzuiop

Related

bash removes consecutive spaces from string [duplicate]

This question already has answers here:
I just assigned a variable, but echo $variable shows something else
(7 answers)
Closed 2 years ago.
I ran into a strange problem that I do not understand. Why are multiple spaces not present in the output of the following command?
$ d='A B'
$ echo $d
A B
use in double quotes:
echo "$d"

How to add a variable to matched expression in sed? [duplicate]

This question already has answers here:
How to find/replace and increment a matched number with sed/awk?
(5 answers)
Closed 4 years ago.
Suppose I have the following Bash script:
#!/bin/bash
INCREMENT_BY=5
sed 's/20000/&+$INCREMENT_BY/g' old > new
I expect all occurrences of 20000 to be replaced by 20005, but instead they are replaced with 20000+$INCREMENT_BY. How can I make this work?
You should use double quote for eval variable, like:
sed "s/20000/$(( $INCREMENT_BY + 2000))/g" old

How to get length of variable bash? [duplicate]

This question already has answers here:
Length of string in bash
(11 answers)
Closed 6 years ago.
I use Cent OS 7, and have written a Bash script.
I tried to get the length of variable:
#!/bin/bash
URL_STRING="1";
VAR_LENGTH=${#URL_STRING}
echo $VAR_LENGTH;
But I get syntax error
Try this code
echo $URL_STRING| awk '{printf("%d",length($0))}' | read asd

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}'

Why this shell script doesn't work? [duplicate]

This question already has answers here:
How do I iterate over a range of numbers defined by variables in Bash?
(20 answers)
Closed 9 years ago.
n=5
for i in {1..$[n]}
do
echo $i
done
it gives:
{1..5}
But I think it should output:
1
2
3
4
5
Why it gives such a strange output?
That is almost a riddle. The expansion of the braces is being done prior to the variable expansion. The bash beginners guide has some good detail on expansion
There are a brazillion ways to do this in bash.
You could start with:
n=5
for i in $(eval echo {1..$n})
do
echo $i
done

Resources