Linux find and replace in string

Spread the love

Some useful ways to manipulate files:

Array: Array could be crated like

myArr=("val1" "val2")

You can see that values are separated through space.

Store multiline string to variable: Use cat command like below:

multilineString=$(cat <<-END
    /* 
      My lines
   */
END
)

Be careful with ‘END’ word. There should be any space before it, otherwise it will considered as a line.

Looping through array: We can loop through arrays as follows:

# Iterate values
for value in "${myArr[@]}"; do

done

#iterate index
for index in "${!myArr[@]}"; do

done

#Accessing a variable based on index
index=0
${myArr[$index]} 
   #Or simply
${myArr[0]} 

The ‘!’ sign indicates to iterate through indexes. ‘@’ sign means we are going to iterate through ‘myArr’

Search through files and store return values in a variable: We will use grep to search for string pattern.

# This way grep command will execute and returned values will be saved to foundValues variable.
foundValues=$(grep pattern filePath)

Split string and select a index:

# We are using cut command after pipe. The delimiter is ':' and index selected is 2 (1 based index).
valueSelectedAfterSplit=$(echo $string | cut -d ":" -f 2)

Search and replace in a string:

 #Command used is: ${main_string/search_term/replace_term}
# In below replace command we replacing ',' with nothing.
 value="${stringToReplaceIn/,/}"

Save value in a variable to a file:

echo "$variableName" > "$targetFileAbsolutePath"

You can add some of your most used commands in comments.

Cheers and Peace out!!!