Skip to main content
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 (...
Olorin's user avatar
  • 4,729
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 ...
Kusalananda's user avatar
  • 356k
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 ...
Ned64's user avatar
  • 9,276
31 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: ...
Kusalananda's user avatar
  • 356k
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/./\&...
Stéphane Chazelas's user avatar
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
northtree's user avatar
  • 359
24 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 ...
Stéphane Chazelas's user avatar
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 ...
Kusalananda's user avatar
  • 356k
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\n' ...
jesse_b's user avatar
  • 41.5k
21 votes
Accepted

What's the purpose of adding a prefix on both sides of a shell variable comparison to a string literal?

The important thing to understand here is that in most shells¹, [ is just an ordinary command parsed by the shell like any other ordinary command. Then the shell invokes that [ (aka test) command with ...
Stéphane Chazelas's user avatar
19 votes
Accepted

Split string on colon in /bin/sh

Just do: case $1 in (*:*) host=${1%:*} port=${1##*:};; (*) host=$1 port=$default_port;; esac You may want to change the case $1 to case ${1##*[]]} to account for values of $1 like [::1] (...
Stéphane Chazelas's user avatar
18 votes
Accepted

How to grep '$$$$$'?

It seems that $ is a special character for end of line? Yep, exactly. And there's an end-of-line on each and every line. You'll need to use \$\$\$\$\$ as the pattern, or use grep -F '$$$$$', to tell ...
ilkkachu's user avatar
  • 148k
16 votes

Padding trailing whitespaces in a string with another character

printf "%.20s:\n\n" "$str=========================" where %.20s is the string truncating format
JJoao's user avatar
  • 12.8k
16 votes

How to compare 2 strings in UNIX shell script?

Simple answer to do so you can use this syntax : if [ "$category" = "$request" ] Spacing is important. Side note, you should use the recent way of doing command subsitition and replace (see article 1 ...
Kiwy's user avatar
  • 9,882
16 votes
Accepted

Build a command dynamically

Don't try to make an executable string. Instead build the arguments in an array and use that when calling tar (you are already using an array properly for EXCLUDE): #!/bin/bash directory=/tmp ...
Kusalananda's user avatar
  • 356k
16 votes
Accepted

Pattern matching in a zsh conditional expression

[ $x = '*test*' ] tests whether the string resulting from expanding $x, which is text, is equal to the string resulting from expanding '*test*', which is *text*. To test whether the value of the ...
Gilles 'SO- stop being evil''s user avatar
15 votes

How to use the 'date' command to display week number of the year?

There are two kinds of week: Monday as first day Sunday as first day So its not all the same when you are in different day of a week(CentOS7): [[email protected]:~]# date Mon Aug 26 18:02:47 CST ...
Valiant Jiang's user avatar
15 votes

In `sed` how can I put one "&" between characters in a string?

Unix utilities: fold -w1|paste -sd\& - Explained: "fold -w1" - will wrap an each input character to its own line fold - wrap each input line to fit in specified width -w, --width=WIDTH ...
zeppelin's user avatar
  • 3,972
15 votes
Accepted

bash - True if the length of string is (non)zero?

[ .. ] follows the same rules as all other commands, namely Word Splitting applies. If OUT is empty (or unset), $OUT will expand to nothing, not even an empty argument. So, [ -n $OUT ] expands to [, -...
ilkkachu's user avatar
  • 148k
14 votes

How to generate a random string?

I use: base64 < /dev/urandom | tr -d 'O0Il1+/' | head -c 44; printf '\n' This gives me 57 possible characters. The string can be copy-pasted (removed + and /) or printed and retyped as the ...
Iiridayn's user avatar
  • 369
13 votes
Accepted

Print a string if the last character is odd

Short awk command: awk '/[13579]$/' file > hostnames_odd.txt [13579] - character class representing the list of allowed digits (odd numbers) $ - the end of the string/line Result: $ cat ...
RomanPerekhrest's user avatar
13 votes
Accepted

Why grep does not work properly in this case?

.... what am I doing wrong? ... apart from making it far more complicated that it needs to be ... you are trying to match multiple spaces and leading spaces that are not in your strings in all of the ...
bu5hman's user avatar
  • 4,851
12 votes
Accepted

completely ignore lines that start with a specific pattern

Without using next, using negation instead. Input: $ cat f.txt GOOD STUFF ---------------- IRRELEVENT DATA ---------------- IGNORE ALL THESE ---------------- END OF IT ---------------- GOOD STUFF I ...
z atef's user avatar
  • 1,123
12 votes
Accepted

Test if variable contains newline (POSIX)

You can put a hard newline in a variable, and pattern match with case. $ cat nl.sh #!/bin/sh nl=' ' case "$1" in *$nl*) echo has newline ;; *) echo no newline ;; esac $ dash nl.sh $'...
ilkkachu's user avatar
  • 148k
12 votes
Accepted

How to POSIX-ly count the number of lines in a string variable?

The simple answer is that wc -l <<< "${string_variable}" is a ksh/bash/zsh shortcut for printf "%s\n" "${string_variable}" | wc -l. There are actually differences in the way <<< and ...
Gilles 'SO- stop being evil''s user avatar
12 votes
Accepted

How to treat a command output as text

You are attempting to execute the contents of $pvs_var as a command, rather than passing the string to awk. To fix this, add an echo or printf in your if statement: if [[ $(echo "$pvs_var" | awk '{ ...
Peschke's user avatar
  • 4,286
12 votes
Accepted

Convert array type variable to string type with space delimiter

If the first character of IFS variable is a space (which it is by default), you can use the star index in double quotes. #! /bin/bash arr[0]=2019-06-26 arr[1]=15:21:54 string="${arr[*]}" printf "'%s'...
choroba's user avatar
  • 49.4k
12 votes
Accepted

Command to keep only a portion of JSON data from each line?

With a proper jq tool: jq -c '{"b": .b}' test.json The output: {"b":"sd"} {"b":"bfgg"}
RomanPerekhrest's user avatar

Only top scored, non community-wiki answers of a minimum length are eligible