523
votes
How to generate a random string?
I am using the openssl command, the swiss army knife of cryptography.
openssl rand -base64 12
or
openssl rand -hex 12
306
votes
Accepted
Split string by delimiter and get N-th element
Use cut with _ as the field delimiter and get desired fields:
A="$(cut -d'_' -f2 <<<'one_two_three_four_five')"
B="$(cut -d'_' -f4 <<<'one_two_three_four_five')"
You can also use ...
164
votes
94
votes
Accepted
Remove last character from string captured with awk
Yes, with substr() you can do string slicing:
... | awk '{if (NR!=1) {print substr($2, 1, length($2)-1)}}'
length($2) will get us the length of the second field, deducting 1 from that to strip off ...
77
votes
Accepted
How to run string with values as a command in bash?
That would be:
eval "$command"
If you want the content of $command to be evaluated as shell code.
If you can't guarantee that $command won't start with - (which would cause eval in some ...
62
votes
Accepted
Why won't the strings command stop?
If GNU cat can't write out what it read, it will exit with an error:
/* Write this block out. */
{
/* The following is ok, since we know that 0 < n_read. */
size_t n = n_read;
if (...
58
votes
Split string by delimiter and get N-th element
Wanted to see an awk answer, so here's one:
A=$(awk -F_ '{print $2}' <<< 'one_two_three_four_five')
B=$(awk -F_ '{print $4}' <<< 'one_two_three_four_five')
Try it online!
56
votes
Delete the last character of a string using string manipulation in shell script
The most portable, and shortest, answer is almost certainly:
${t%?}
This works in bash, sh, ash, dash, busybox/ash, zsh, ksh, etc.
It works by using old-school shell parameter expansion. ...
55
votes
Accepted
What is the application of `rev` in real life?
The non-standard rev utility is useful in situations where it's easier to express or do an operation from one direction of a string, but it's the reverse of what you have.
For example, to get the last ...
51
votes
How to generate a random string?
Inspired by Pablo Repetto I ended up with this easy to remember solution:
shuf -er -n20 {A..Z} {a..z} {0..9} | tr -d '\n'
-e echoes the result
-r allows any character to appear multiple times
-n20 ...
44
votes
Split string by delimiter and get N-th element
Using only POSIX sh constructs, you can use parameter substitution constructs to parse one delimiter at a time. Note that this code assumes that there is the requisite number of fields, otherwise the ...
43
votes
Accepted
Why does this script work in the terminal but not from a file?
What is sh
sh (or the Shell Command Language) is a programming language described by the POSIX
standard.
It has many implementations (ksh88, dash, ...). bash can also be
considered an implementation ...
37
votes
Accepted
Bash - Integer expression expected
The test command, also named [, has separate operators for string comparisons and integer comparisons:
INTEGER1 -eq INTEGER2
INTEGER1 is equal to INTEGER2
vs
STRING1 = STRING2
the strings are equal
...
36
votes
How to uppercase the command line argument?
Be careful with tr unless A-Z is all you use. For other locales even '[:lower:]' '[:upper:]' fails, only awk's toupper and bash (v4+) works:
$ str="abcåäö"
$ echo "$str" | tr '/a-...
36
votes
How do I parse out just the date from 2017-03-08T19:41:26Z?
To extract the part before T, with POSIX shells:
time=2017-03-08T19:41:26Z
utc_date=${time%T*} # as already said
Or to be Bourne compatible or for non-POSIX shells:
expr "$time" : '\(.*\)T'
...
35
votes
Accepted
Test if a string contains a substring
You need to interpolate the $testseq variable with one of the following ways:
$file == *_"$testseq"_* (here $testseq considered as a fixed string)
$file == *_${testseq}_* (here $testseq considered as ...
35
votes
Accepted
How to split a string by the third .(dot) delimiter
Used sed for example:
$ echo 'version: 1.8.0.110' | sed 's/\./-/3'
version: 1.8.0-110
Explanation:
sed s/search/replace/x searches for a string and replaces it with another string. x determines which ...
31
votes
How to generate a random string?
To generate password with the highest entropy possible with standard Linux tools that are built into every distribution I use:
< /dev/urandom tr -cd "[:print:]" | head -c 32; echo
This outputs ...
30
votes
Accepted
Using the diff command to compare two strings?
Yes, you can use diff on two strings, if you make files from them, because diff will only ever compare files.
A shortcut way to do that is using process substitutions in a shell that supports these:
...
26
votes
Accepted
Does bash support back references in parameter expansion?
ksh93 and zsh have back-reference (or more accurately1, references to capture groups in the replacement) support inside ${var/pattern/replacement}, not bash.
ksh93:
$ var='Blah: -> r1-ae0-2 / [...
26
votes
Accepted
In `sed` how can I put one "&" between characters in a string?
With GNU sed:
sed 's/./\&&/2g'
(substitute every (g) character (.) with the same (&) preceded with & (\&) but only starting from the second occurrence (2)).
Portably:
sed 's/./\...
25
votes
How to generate a random string?
Use the xxd command to specify length (via -l),
which works both in Linux and macOS.
See the xxd(1) man page
or the Linux xxd Command Tutorial for Beginners (with Examples).
xxd -l16 -ps /dev/urandom
24
votes
Test if a string contains a substring
file="JetConst_reco_allconst_4j2t.png"
testseq="gen"
case "$file" in
*_"$testseq"_*) echo 'True' ;;
*) echo 'False'
esac
Using case ... esac is one of the simplest ways to ...
23
votes
Why does this script work in the terminal but not from a file?
Adding to the excellent answer from @Hunter.S.Thompson I'd like to point out that the non-portable part of the script is
pdf_file="${html_file/.html/.pdf}"
The ${variable/search/replace} is a GNU ...
23
votes
Padding trailing whitespaces in a string with another character
filler='===================='
string='foo'
printf '%s\n' "$string${filler:${#string}}"
Gives
foo=================
${#string} is the length of the value $string, and ${filler:${#string}} is the ...
23
votes
Accepted
How to split a string by ':' character in bash/zsh?
The : there is any arbitrary character:
You can use:
parts=(${(s/:/)str})
Some common character pairs are also supported like:
parts=(${(s[:])str})
If you're going to use the @ flag to preserve ...
22
votes
Accepted
How to split a string in two substrings of same length using bash?
Using parameter expansion and shell arithmetic:
The first half of the variable will be:
${var:0:${#var}/2}
The second half of the variable will be:
${var:${#var}/2}
so you could use:
printf '%s\...
21
votes
Accepted
How to insert a string into a text variable at specified position
To insert the text j into the variable text at position p (counting from zero):
p=5
text="$(seq 10)" ## arbitrary text
text="${text:0:p}j${text:p}"
To insert the text j before the ...
Only top scored, non community-wiki answers of a minimum length are eligible
Related Tags
string × 798bash × 322
shell-script × 169
sed × 122
shell × 119
grep × 90
awk × 88
text-processing × 73
regular-expression × 53
linux × 49
search × 44
variable × 41
replace × 38
files × 32
scripting × 30
zsh × 26
array × 26
filenames × 24
command-line × 21
find × 20
quoting × 19
test × 17
wildcards × 13
cut × 13
date × 12