Unix – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 09 Aug 2025 10:35:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Unix – Java2Blog https://java2blog.com 32 32 Bash Add Character to String https://java2blog.com/bash-add-character-to-string/?utm_source=rss&utm_medium=rss&utm_campaign=bash-add-character-to-string https://java2blog.com/bash-add-character-to-string/#respond Thu, 04 May 2023 09:08:02 +0000 https://java2blog.com/?p=23659

We can also use these methods to add a string to the given string as well.

Using $ Operator

Use the $ operator to add character to string in Bash.

str="Hell"
str="${str}o"
echo $str
Hello

the${str} is used to expand the value of the str variable and then appends the string o to it, resulting in the string Hello. The final value of str is then printed to the terminal using the echo command, which outputs Hello.

If you want to add characters between the String, you can use it as following:

ch="e"
str="H${ch}llo"
echo $str
Hello

Using + Operator

Use the + concatenation operator to add a character to the string in Bash.

str="Hello"
str+="o"
echo $str
Hello

In the above code, a variable called str is declared and initialized to the string Hell. We then use the +concatenation operator to add a character o to the end of str. Finally, we use the echo command to print the value of str, which is Hello.

Using printf Command

Use the printf command to add a character to the string in Bash

str="Hell"
printf -v str '%so' "$str"
echo $str
Hello

In the above code, the printf -v str '%so' "$str" uses the printf command to format a string and assign it to the variable str. The -v option tells printf to assign the formatted string to the variable specified after it. The format string '%so' specifies that the value of $str should be inserted at the position of %s, followed by the string o. The resulting string is then assigned to str.

Add Character to String at beginning

If you want to add character at beginning, you can easily do it using ${} syntax.

ch="H"
str="${ch}ello"
echo $str
Hello

Add Character to String at the end

If you want to add character at end, you can easily do it using ${} syntax.

ch="H"
str="Hell${ch}"
echo $str
Hello

Considering the above solutions, the concatenation operator, $ operator, and printf methods can add a character to the string. You can choose any of them depending on your use case.

That’s all about bash add character to String.

]]>
https://java2blog.com/bash-add-character-to-string/feed/ 0
Bash Create Folder if Not Exists https://java2blog.com/bash-create-folder-if-not-exists/?utm_source=rss&utm_medium=rss&utm_campaign=bash-create-folder-if-not-exists https://java2blog.com/bash-create-folder-if-not-exists/#respond Wed, 03 May 2023 11:56:28 +0000 https://java2blog.com/?p=23653

To run the following commands, directly write the command in the bash terminal and execute them.

Using mkdir -p Command

Use the mkdir -p command to create folder if not exists in Bash

mkdir -p /path/to/directory

The mkdir is used to create the directory. The -p created all the intermediate directories if they didn’t exist.

The /path/to/directory is the path to the directory you wanted to create. The command created the directory that does not exist and also parent directories that did not exist for the given path.

For example:

mkdir -p test/bash/scripts

It will create folders test, test/bash, and test/bash/scripts if they don’t exist.

Using test -d Command with || Operator

Use the Test -d command to test whether a directory/folder exists. The mkdir command creates a directory/folder if it does not exist.

test -d /path/to/directory || mkdir /path/to/directory

The test -d command is used to check whether the directory exists. The OR operator (||) executes the command on the right-hand side of itself if the left-hand side command is not True. The mkdir is used to create the directory. The /path/to/directory is the path to the created directory.

The following commands cannot be run directly on the terminal but by calling the script file. First, make a bash file using a text editor and write the code in that file. Then save the file with the .sh extension.

After saving the file, open the terminal and execute the source FileName.sh command to run the bash script file. Note that the following conditional commands can be used to check and create a folder if it does not exist in bash.

Using if Statement

The if conditional statement tests whether a directory/folder exists. If the condition meets and the directory/folder does not exist, it will create a directory/folder using the mkdir command.

if [ !-d /path/to/directory]; then
    mkdir /path/to/directory
fi

The command checked the directory path /path/to/directory does not exist, the test command returned True, and the mkdir command was executed to create the directory. If the directory already exists, the test command returns False, and the script skipped themkdir command and continues executing subsequent commands.

In the above example, [] is the test command.

Using mkdir with if Statement

Use if conditional statement with mkdir command to create folder if it not exists in Bash..

if ! mkdir /path/to/directory 2>/dev/null && [ ! -d /path/to/directory]; then
    echo "Failed to create directory" >&2
fi

The mkdir command returned True if the folder /path/to/directory does not exist. If the directory already exists, or if the mkdir command failed, the next condition will be executed, testing whether the directory exists. If the directory does not exist, the script executes the echo command and displays an error message Failed to create directory to the console.

Using if Statement with stat Command

The if conditional statement with stat command to create folder if it not exists in Bash.

if [ ! -d /path/to/directory]; then
    stat /path/to/directory 2>/dev/null || mkdir /path/to/directory
fi

The if statement was True; if the directory /path/to/ directory does not exist, the stat command will be executed. If the stat command failed (i.e., the directory does not exist), the mkdir command was executed to create the directory. If the directory already exists, the stat command succeeded, and the mkdir command is not executed.

That’s all about bash create folder if not exists.

]]>
https://java2blog.com/bash-create-folder-if-not-exists/feed/ 0
If Not Condition in Bash https://java2blog.com/if-not-condition-bash/?utm_source=rss&utm_medium=rss&utm_campaign=if-not-condition-bash https://java2blog.com/if-not-condition-bash/#respond Tue, 02 May 2023 09:39:30 +0000 https://java2blog.com/?p=23588 In Bash, figuring out how you interpret the term if not condition before digging into the solutions is mandatory. For example, are you taking as negating the condition/expression, which means make the condition/expression False if it is True and vice versa? Or, you want to make some comparisons to assess inequality; this comparison can be of numbers or strings. We covered all the use cases below, and you can jump around to find your desired solution.

Comparing Numbers/Strings for Inequality

Use the -ne operator to check if two numbers are not equal to each other in Bash.

#!/bin/bash
number1=8
number2=3
if [ $number1 -ne $number2 ]
then
   echo "The '$number1' and '$number2' are not equal."
fi
The '8' and '3' are not equal.

Use != operator to check if strings are not equal to each other in Bash.

#!/bin/bash
string1='Mehmood'
string2='Ali'
if [ $string1 != $string2 ]
then
   echo "The '$string1' and '$string2' are not equal."
fi
The 'Mehmood' and 'Ali' are not equal.

We can also assign string values to variables without wrapping them around with single or double quotes. See the following example.

#!/bin/bash
string1=Mehmood
string2=Ali
if [ $string1 != $string2 ]
then
   echo "The '$string1' and '$string2' are not equal."
fi
The 'Mehmood' and 'Ali' are not equal.

Don’t add white space before and/or after the = sign while assigning value to the variables, such as string1= 'Mehmood' or string1 = Mehmood; otherwise, you will get an error illustrating the command not found.

Negating the Condition/Expression

Use the ! operator to negate the value of the specified condition meaning turn the resulting value to True if it is False and vice versa.

#!/bin/bash
number1=8
number2=3
if ! [ $number1 -ne $number2 ]
then
    echo "The '$number1' and '$number2' are not equal."
else
    echo "The '$number1' and '$number2' are equal."
fi
The '8' and '3' are equal.

This example is similar to the one where we compared two numbers using the -ne operator. In the above code, we negated the condition, which means the output of the [ $number1 -ne $number2 ] condition was True because 8 is not equal to 3, but we turned this result into False using ! operator; that’s why if block was not executed but else block.

Similarly, use the ! operator to negate the value of the specified condition for string values by turning the resulting value to True if it is False and vice versa.

#!/bin/bash
string1=Mehmood
string2=Ali
if ! [ $string1 != $string2 ]
then
    echo "The '$string1' and '$string2' are equal."
fi

For this code, the [ $string1 != $string2 ] resulted in True, but the ! operator made it False, so the echo command within the if block was not executed and we didn’t get any output. So let’s practice the above example with an expression as follows.

Use the ! operator to negate the value of the specified expression for string values by turning the resulting value to True if it is False and vice versa.

#!/bin/bash
string=Mehmood
if  ! [ -z "$string" ]
then
    echo "The specified string is not empty."
else
    echo "The specified string is empty."
fi
The specified string is not empty.

Here, we used -z to check if the specified string is empty, so the [ -z "$string"] expression returned False because $string is not empty, but it was turned to True due to using ! operator and resulted in if block execution; otherwise, the else block would be executed.

]]>
https://java2blog.com/if-not-condition-bash/feed/ 0
Bash Split String and Get Last Element https://java2blog.com/bash-split-string-and-get-last-element/?utm_source=rss&utm_medium=rss&utm_campaign=bash-split-string-and-get-last-element https://java2blog.com/bash-split-string-and-get-last-element/#respond Sun, 16 Apr 2023 10:35:59 +0000 https://java2blog.com/?p=23610 Using read Command

Use the read command with parameter expansion to split the string and get the last element in Bash.

#!/bin/bash
myString="Hello:World:How:are:you?"
read lastElement <<< "${myString##*:}"
echo "The last element is: $lastElement"
The last element is: you?

In the above example, the read command is used with the ${myString##*:} parameter expansion to get the last element of the string which is then assigned to the lastElement variable using the <<< operator. Here, the ## operator removes everything up to the string"s last colon(:). In Bash, the ## operator performs a greedy match, meaning it removes the longest possible match of the pattern from the beginning of the string.

${
  myString  <-- from variable myString
  ##   <-- greedy front trim
  *    <-- matches anything
  :    <-- until the last ':'
 }

For example, in the above variable myString="Hello:World:How:are:you?", the *: pattern matched everything up to the last colon, and the ## operator is used to remove all of it, leaving only the last element of the string you?. You can replace the colon(:) with any character that we want to match.

Let"s see another example where you want to get the last element from the path.

#!/bin/bash
path="/path/to/my/file.txt"
read filename <<< "${path##*/}"
echo "The last element of the Path is: $filename"
The last element of the Path is: file.txt

Here, the ${path##*/} parameter expansion is used to get the last element of the path "/path/to/my/file.txt". The */ pattern matches everything up to and includes the last forward slash in the path, and the ## operator removed all of it, leaving only the file name.

Do this if you want to get the last element of your current working directory.

#!/bin/bash
dir=$(pwd);
echo "Current Working Directory is: $dir"
read filename <<< "${dir##*/}"
echo "Last element is: $filename"
Current Working Directory is: /home/cg/root/642c71d615527
Last element is: 642c71d615527

Using tr Command

Use the tr command to split the string and get the last element in Bash.

#!/bin/bash
myString="This:is:a:String"
lastElement=$(echo "$myString" | tr ':' '\n' | tail -n 1)
echo "The last element is: $lastElement"
The last element is: String

The tr command in Bash is typically used for transforming and deleting characters in a string or a file. Various types of transformation can be done by using this command, such as searching and replacing text.

In the above example, the input string "This:is:a:String" is first piped to the tr command, which replaces all occurrences of a delimiter character(:) with newline characters(\n), effectively splitting the string into multiple lines. Then, the output of tr is passed to the tail command. The tail command is a utility in Linux and Unix operating systems used to print the last few lines of a string or a file.

Here, the -n option, followed by the number 1, is used to print only the last line. This allows us to extract the last element of a string split by tr.

Using Cut Command

Use the cut command to split the string and get the last element in Bash.

#!/bin/bash
string="Apple,Banana,Orange"
lastElement=$(echo "$string" | rev | cut -d ',' -f 1 | rev)
echo "The last element is: $lastElement"
The last element is: Orange

In this example, the "Apple,Banana,Orange" string contained text with commas as separators. To extract the last element of this string, the rev command is used to reverse the string. Then, the cut command splits the reversed string at the first comma (,) and selects the first field (-f 1).

Finally, the rev command is used again to reverse the resulting string to obtain the last element.

Using awk Command

Use the awk command to split the string and get the last element in Bash.

#!/bin/bash
myString="some:text:with:colons"
lastElement=$(echo $myString | awk -F ':' '{print $NF}')
echo "The last element is: $lastElement"
The last element is: colons

In the above code snippet, the awk command is used to extract the last element of this string "some:text:with:colons" with the -F option to specify the colon (:) as the field separator.

The NF variable is automatically set by awk and contains the number of fields in the current record. Here, It is used to reference the last field in a record, which is the last element of the string we want to extract.

Using grep Command

Use the grep command to split the string and get the last element in Bash.

#!/bin/bash
myString="some text with spaces"
lastElement=$(echo $myString | grep -oE '[^ ]+$')
echo "The last element is: $lastElement"
The last element is: spaces

In this example, the string "some text with spaces" contained text separated by spaces. The grep command is used with the -oE parameters to get the last element of this string.

  • The -o parameter tells the grep command to output only the matching text.
  • The -E parameter enables regular expressions.

The regular expression [^ ]+$ is used to find one or more characters that are not spaces ([^ ]) at the end of the line ($).

Using sed Command

Use the sed command to split the string and get the last element in Bash.

#!/bin/bash
myString="this is a sample string"
lastElement=$(echo "$myString" | sed 's/.* //')
echo "The last element is: $lastElement"
The last element is: string

In this example, the sed command is used with the s (substitute) command to match everything before the last space character in the input string and replace it with nothing.

In Bash, the sed command performs text transformations on the input text. The "s" character is used as the substitute command in sed, which is used to search and replace a given pattern in the input text. In addition, the regular expression .* is used to search any sequence of characters (except for newline) zero or more times; in other words, it matches everything before the last space character in the input text.

The last element in the string is effectively extracted by replacing everything before the last space character with nothing.

Using basename Command

Use the basename command to split the string and get the last element in Bash.

#!/bin/bash
path="/path/to/my/file.txt"
lastElement=$(basename "$path")
echo "The last element is: $lastElement"
The last element is: file.txt

In the above example, the path variable is set to the file path "/home/user/Documents/file.txt". Then, this variable is passed to the basename command using the $() syntax to execute the command and capture its output. In Bash, the basename command is used to get the last element of the file path. That, in this case, is the file name file.txt.

Note that the basename command removes any leading directory components from the input path and returns only the final file or directory name. If the input path ends with a trailing slash, the basename command returns an empty string as output.

Using IFS Command

Use the IFS (Internal Field Separator) variable with a delimiter to split the string and get the last element in Bash.

#!/bin/bash
string="first second third fourth"
IFS=' ' read -ra arr <<< "$string"
echo "The last element is: ${arr[-1]}"
The last element is: fourth

The IFS variable is used with a space delimiter to split the string in the above example. And the read command is used with the -ra option to read the input string into an array called arr. Here, the -a parameter tells the read command to read the input into an array, and the -r parameter tells it to treat backslashes as literal characters.

Then, the <<< syntax is used to pass the input string as the input to the read command. Finally, the ${arr[-1]} is used to access the last element of the arr array, the fourth string.

Let"s see another example below:

#!/bin/bash
string="first:second:third:fourth"
IFS=':' read -ra arr <<< "$string"
echo "The last element is: ${arr[-1]}"
The last element is: fourth

In this example, the last element of the string is extracted using the IFS variable, which is set to a colon character ":". Splitting the string into words tells the shell to use a : as the delimiter.

Without Using the IFS variable

Use space as a delimiter to split the string in bash without the IFS variable and get the last element.

#!/bin/bash
string="first second third fourth"
readarray -d " " -t words<<< "$string"
echo "The last element is: ${words[-1]}"
The last element is: fourth

This code snippet split the string "first second third fourth" into words using the readarray command and stored them in an array called words. Here, the -d option specifies the space character as a delimiter, and the -t parameter removes any trailing newlines. Next, the last element of a string is extracted from the words array using ${words[-1]}.

Let"s use any symbol as a delimiter other than a space character.

#!/bin/bash
string="first@second@third@fourth"
readarray -d "@" -t words<<< "$string"
echo "The last element is: ${words[-1]}"
The last element is: fourth

In this example, the string is split into a words array using the @ delimiter to extract the last element.

That’s all about bash split String and get last element.

]]>
https://java2blog.com/bash-split-string-and-get-last-element/feed/ 0
Add Comma to End of Each Line in Bash https://java2blog.com/bash-add-comma-to-end-of-each-line/?utm_source=rss&utm_medium=rss&utm_campaign=bash-add-comma-to-end-of-each-line https://java2blog.com/bash-add-comma-to-end-of-each-line/#respond Sun, 16 Apr 2023 05:30:18 +0000 https://java2blog.com/?p=23602 1. Overview

Adding characters like commas to the end of each line in a text file is a common operation in file processing and data manipulation. This task can be especially useful in formatting data files for CSV conversion or similar purposes.

2. Introduction to Problem Statement

Imagine we have a text file named input.txt containing the following 3 lines:
For example:

John
Mary
Sam

Our goal is to add comma to the end of each line. Expected output is:

John,
Mary,
Sam,

We will also see how to add comma at the end of each line in a file, except for the last line.

Now, let’s continue learning various methods to add a comma at the end of each file line.

3. Using sed Command

The sed (Stream Editor) is a powerful text processing tool ideal for pattern-based transformations.

Let’s use sed command to add comma to each line of the file:

sed -i 's/$/,/' input.txt

On MAC OS, we can use following command:

sed -i '' -e 's/$/,/' input.txt
John,
Mary,
Sam,

In the above code, the sed command performs a substitution operation (s) on each input file line (input.txt); the expression $ matches the end of each line, and the comma is added with /,/. -i option edits file in-place.

To add a comma to each line except the last one, we can use following command:

sed -i '$!s/$/,/' input.txt

$!: This is an address specifier in sed. The dollar sign ($) represents the last line of the file. The exclamation mark (!) negates the address, meaning the subsequent command will be executed on all lines except the last line.
s/$/,/: This subsequent command is similar to adding comma to each line of the file.

4. Using awk Command

The awk is a programming language designed for text processing and offers robust capabilities for manipulating file content.

Let’s use awk to achieve our goal:

awk -i inplace '{print $0","}' input.txt
John,
Mary,
Sam,

The command awk in the above code reads input data from a file and executes operations on each input line following the user-specified rules. For example, the'{print $0","}' prints each input file line, followed by a comma.

To add comma to each line except last one, we can use the following awk command:

awk -i inplace '{printf "%s%s",sep,$0; sep=",\n"} END{print ""}' file

{printf "%s%s",sep,$0; sep=",\n"}: This is the main action block of the script, executed for each line of the input file.
Let’s deep dive into this main block:

  • printf "%s%s",sep,$0;: Here, printf is used for formatted printing. %s is a format specifier for a string. It prints two strings: sep (initially empty) and $0 (the entire current line from the file).
  • sep=",\n": After printing the first line, sep is set to a comma followed by a newline character. This means that for the subsequent lines, a comma and a newline will be printed before the line content.
  • END{print ""}: This is executed after all lines of the file have been processed. It simply prints a newline character. This ensures that the output ends with a newline, which is a good practice in Unix-like systems to properly end the last line.

5. Using Bash Loop

For more control, a Bash script can read and write each line of the file, appending a comma.

while IFS= read -r line; do
    echo "${line}," >> temp.txt
done < input.txt && mv temp.txt input.txt

The above script reads each line of the file and appends a comma, and writes the result to a temporary file, then renames it.

6. Using vim editor

If we want to do it using vim editor, we can use expression :%s/$/,/g.
Here are steps:

  • Open the file using vim. vi intput.txt
  • Use expression :%s/$/,/g and press enter.

It will add a comma to the end of every line in bash.

7. Conclusion

Appending a comma to the end of each line in a file can be efficiently done using sed, awk, or a Bash loop. sed is generally the fastest and most efficient, especially for larger files. awk offers a balance between speed and flexibility, providing additional text processing options if needed.

While Bash loops offer the most control, they are less efficient and are better suited for smaller files or less performance-critical tasks.

]]>
https://java2blog.com/bash-add-comma-to-end-of-each-line/feed/ 0
Round to 2 Decimal Places in Bash https://java2blog.com/bash-round-to-2-decimal-places/?utm_source=rss&utm_medium=rss&utm_campaign=bash-round-to-2-decimal-places https://java2blog.com/bash-round-to-2-decimal-places/#respond Sun, 16 Apr 2023 05:22:02 +0000 https://java2blog.com/?p=23650 1. Overview

In Bash scripting, dealing with numbers and specifically rounding them to a certain number of decimal places is a common task. For example, given a number like 3.14159, the goal is to round it to two decimal places, resulting in 3.14.

This article explores various methods to achieve this in Bash, focusing on rounding to two decimal places. We will compare each method’s performance and delve into each command’s details.

2. Using printf Command

The printf command in Bash is similar to the printf function in C. It is used to format the output.

Here is the syntax:

print options [format specifier] arguments

Format specifier provides the format of output. In this case, we want to round the number to 2 decimal places, and that’s the reason we can put the format as "%.2f".

number=1.855678
rounded_number=$(printf "%.2f\n" $number)
echo $rounded_number
1.86

The explanation of the above code snippet is as follows:
%.2f is format specifier here.

  • % introduces format specifier.
  • .2 indicates that the number should be rounded to 2 decimal places.
  • f stands for floating-point number.

\n is a newline character to ensure that output is followed by a new line.
$number is a variable containing the number to be formatted.

printf is fast and efficient for formatting numbers. It’s built into the shell and doesn’t require spawning a new process.

3. Using awk Command

The awk is a text processing and data manipulation tool.. We can use the awk command with format specifier as %.2f as below:

number=1.855678
echo $number | awk '{printf("%.2f\n", $0)}'
1.86

The explanation of the above code fence is as follows:

  • The echo $number sends the number to the awk command.
  • | pipes output of echo to awk.
  • Inside awk, {printf "%.2f\n", $0} is action performed on the given input.
    • printf "%.2f\n" is similar to the printf command.
    • $0 represents the entire line of the input, a number in this case.

4. Using bc

The bc is an arbitrary precision calculator language. Let’s use bc to round the number to 2 decimal places.

number=1.855678
rounded_number=$(echo "scale=2; $number/1"| bc)
echo $rounded_number
1.85

Please note that above bc command doesn’t round the decimal but truncates to 2 decimal places.

We can use the following command to do the round rather than truncate:

number=1.855678
rounded_number=$(echo "scale=2; ($number+0.005)/1"| bc)
echo $rounded_number
1.86

5. Using Python

Invoking Python for arithmetic operations provides high precision and is useful if the script interacts with Python or requires advanced mathematical functions.

number=1.855678
python -c "print(round(number, 2))"
  • python -c allows running a Python command as a string from the shell.
  • print(round(number, 2)) calls Python’s round function, rounding the number to two decimal places.
  • The number in the Python command is the shell variable and needs to be passed correctly.

This is an excellent solution in case our script already interacts with Python. If not, it can cause extra overhead due to a call to the external interpreter.

6. Conclusion

In this article, we have discussed different ways to round to 2 decimal places.

printf is fast and efficient for formatting numbers. It’s built into the shell and doesn’t require spawning a new process. This makes it an excellent choice for basic formatting.

bc and awk offer more precision but at the cost of performance. Python is powerful and precise but is the slowest option here due to the overhead of invoking an external interpreter.

]]>
https://java2blog.com/bash-round-to-2-decimal-places/feed/ 0
Bash Log Output to File https://java2blog.com/bash-log-output-to-file/?utm_source=rss&utm_medium=rss&utm_campaign=bash-log-output-to-file https://java2blog.com/bash-log-output-to-file/#respond Sun, 16 Apr 2023 05:00:43 +0000 https://java2blog.com/?p=23662 Using Redirect Operator

To log the output of a bash command to a file, use the redirect operator.

There are two types of redirect Operator:

  • > (Standard Output Redirect Operator): It redirects the output of a command to a file and overwrites the file’s contents.

  • >> (Standard Output Append Operator): It appends the command’s output to the end of the file without overwriting.

Suppose a scenario in which you want to store the names and emails of students in a log file.

echo -p "Enter your Name: "
read name
echo "Name: $name" > studentLog.txt

In this example, the student’s name is taken as input and stored in a file called studentLog.txt. Here, > redirected the standard output of the echo command to the studentLog.txt file instead of displaying it on the terminal. On execution of the above command, check the file studentLog.txt is created in your current working directory containing the student’s name.

The > operator will create a file if it does not exist, and if it does exist, the existing contents will be overwritten.

The redirect operator can be helpful when saving the output to the file. It redirects the command output to a file instead of displaying it on the console. This is beneficial for storing information that may be required later or generating reports based on the command output. Output can be anything like maintaining records of student results or student information.

Let’s take some more information from the user and store it in the file.

echo "Enter your Email Address: "
read email
echo "Email : $email">studentLog.txt

The student’s email is taken and stored in the email variable in this code snippet. Here, the > operator redirects the standard output of the echo command to the studentLog.txt file, which will overwrite its previous contents (which have the student’s name).

Therefore, after running this code, check the studentLog.txt file; you will see that it now contains the email address instead of the previous content. Note that the file name studentLog.txt is the same as the one generated in the previous example.

If you do not want to overwrite the file’s content, use the >> operator.

$ echo "I am using append operator" >> studentLog.txt

In Bash, the append operator >> append the command output to an existing file instead of overwriting it. We can observe the output of the echo command will append at the end of the studentLog.txt file without deleting its existing contents.

Let’s see another example where you want to redirect the list of all the files in the current directory to the myfiles.txt file.

ls >> myfiles.txt

In this example, the ls command output is logged to the myfiles.txt file. Note that only the standard output is redirected to the file. The command will still be displayed on the terminal if it generates any error message. To redirect the standard error to a file as well, you can use the 2> operator instead of the > operator:

ls > filelist.txt 2> errorlog.txt

In this example, the standard output of the ls command is redirected to filelist.txt, and the standard error is redirected to errorlog.txt. If either file already exists, it will be overwritten; otherwise, it will be created.

Using tee command:

To log the output of a bash command to a file, use the tee command.

echo -p "Enter your Name: "
read name
echo "Name: $name" | tee studentLog2.txt
Enter your name: John
Name: John

In this example, the tee command is used with the echo command to write the output to the file named studentLog2.txt and display it in the terminal window. In Bash, the tee command reads from standard input, writes to standard output on the console window, and writes the same output to a log file. If the given file does not exist, it will be created. The tee command will overwrite its contents if it does exist.

Using the tee command, we can display the output on the terminal and save it to a file simultaneously.

If you want to append the output to an existing file instead of overwriting it use the tee command with the -a parameter :

echo -p "Enter your Email Address: "
read email
echo "Email Address: $email" | tee -a studentLog2.txt
Enter your Email Address: john@gmail
Email Address: [email protected]

On the execution of the command, the email john@gmail address taken in the above code is displayed on the terminal window and appended at the end of the studentLog2.txt file without deleting its existing contents.

That’s all about bash log output to file.

]]>
https://java2blog.com/bash-log-output-to-file/feed/ 0
Bash Remove Special Characters from String https://java2blog.com/bash-remove-special-characters-from-string/?utm_source=rss&utm_medium=rss&utm_campaign=bash-remove-special-characters-from-string https://java2blog.com/bash-remove-special-characters-from-string/#respond Sat, 15 Apr 2023 19:23:33 +0000 https://java2blog.com/?p=23624 Using Parameter Expansion

Use the parameter expansion with regex to remove the special characters from a string in Bash.

#!/bin/bash
string="Hello World! This is a test string."
new_string="${string//[^[:alnum:]]/""}"
echo "The Modified String: $new_string"
The Modified String: HelloWorldThisisateststring

In this example, the parameter expansion removes all special characters from the "Hello World! This is a test string." string. We can observe that our input string contained two special characters, the exclamation marks ! and the space character removed in the modified string.

Here’s a breakdown of the ${string//[^[:alnum:]]/""} expression:

  • string is the input string we want want to modify.
  • // is a pattern substitution operator that replaces all occurrences of a [^[:alnum:]] pattern with an empty string.
  • [^[:alnum:]] is a regular expression pattern that matches any character that is not alphanumeric. The ^ symbol inside the square brackets means not, so this pattern matches any character, not in the [:alnum:] character class. The [:alnum:] character class represents all alphanumeric characters (letters and digits).
  • "" is an empty string used as the replacement string.

Using sed Command

Use the sed command to remove the special characters from a string in Bash.

#!/bin/bash
string="Hi, it's John. How are you?"
new_string=$(echo "$string" | sed 's/[^[:alnum:]]//g')
echo "The Modified String: $new_string"
The Modified String: HiitsJohnHowareyou

This example used the sed command to replace all non-alphanumeric characters with an empty string. The substitution operation(s) is used to replace the pattern [^[:alnum:]] with an empty string. Here, the // indicates that we want to replace the pattern with an empty string globally, and g is a flag that tells sed to perform the substitution operation on all matches in the input string, not just the first match.

Using tr Command

Use the tr command to remove the special characters from a string in Bash.

#!/bin/bash
string="My email is [email protected]"
new_string=$(echo "$string" | tr -dc '[:alnum:]')
echo "The Modified String: $new_string"
The Modified String: Myemailisabcgmailcom

In the above example, the tr command deleted all characters not alphanumeric from the "My email is [email protected]" string. In other words, it is used to remove all special characters. Here, in the-dc parameter, d means delete and c means character. This -dc parameter tells the tr command to delete all characters that do not match the specified character set [:alnum:] (which matches all alphanumeric characters).

Using awk Command

Use the awk command to remove the special characters from a string in Bash.

#!/bin/bash
string="The phone number of the company is :(555) 555-1234"
new_string=$(echo "$string" | awk '{gsub(/[^[:alnum:]]/,"")}1')
echo "The Modified String: $new_string"
The Modified String: Thephonenumberofthecompanyis5555551234

In this bash example, the awk command removes the special characters from the "The phone number of the company is :(555) 555-1234" string and replaces all non-alphanumeric characters with an empty string. Here, the gsub function of the awk command is used to replace the pattern [^[:alnum:]] with an empty string "", and 1 is used to print the modified string.

Using grep Command

Use the grep command to remove the special characters from a string in Bash.

#!/bin/bash
string="The phone number of company is :(555) 555-1234"
new_string=$(echo "$string" | grep -oE '[[:alnum:]]+' | tr -d '\n')
echo "The Modified String: $new_string"
The Modified String: Thephonenumberofcompanyis5555551234

The grep command is used in the above example to match all alphanumeric characters in the string. The -o parameter outputs only the matching pattern, and the -E option enables extended regular expressions.

Here, the tr command removes any newline characters from the output of $new_string, effectively printing the output in a single line.

That’s all about bash remove special characters from String.

]]>
https://java2blog.com/bash-remove-special-characters-from-string/feed/ 0
Bash Get Absolute Path from Relative Path https://java2blog.com/bash-get-absolute-path-from-relative-path/?utm_source=rss&utm_medium=rss&utm_campaign=bash-get-absolute-path-from-relative-path https://java2blog.com/bash-get-absolute-path-from-relative-path/#respond Sat, 15 Apr 2023 19:06:42 +0000 https://java2blog.com/?p=23433 When working with shell scripts, it’s common to need to get the absolute path of a file or directory from its relative path. However, before we dive into how to get the absolute path from a relative path, we must learn the difference between the two types of paths.

The relative path is relative to the current working directory. For instance, if the current working directory is home/user, which contains a text file named File1.txtin the directory /home/user/documents, the relative path to the file would be documents/File1.txt.

An absolute path, on the other hand, is a path that starts from the root directory of the file system. Using the same example above, the file’s absolute path would be /home/user/documents/File1.txt.

Now you are aware of the directory details, let us proceed with learning about obtaining an absolute path from relative path.

Using readlink Command

Use the readlink command to get an absolute path from a relative path in Bash.

readlink -f documents/File1.txt
/home/user/documents/File1.txt

In the above code, the -f option specifies that we want readlink to output the full path (i.e., the absolute path), and documents/File1.txt is the relative path to the file we want to get the absolute path for.

Using realpath Command

Use the realpath command to get an absolute path from a relative path in Bash.

realpath documents/File1.txt
/home/user/documents/File1.txt

In the above code snippet, we used the realpath command to retrieve the absolute path of File1.txt using the relative path documents/File1.txt, realpath resolved the relative path to an absolute path by starting at the current directory (/home/user/) and working its way up the directory tree until it reached the root directory.

Then, it combined the relative path with the absolute path of the current directory to get the complete absolute path of File1.txt, which was /home/user/documents/File1.txt.

Using pwdCommand

Use the pwd command to get an absolute path from a relative path in Bash.

pwd
relative_path="documents/File1.txt"
absolute_path="$(pwd)/$relative_path"
echo $absolute_path
/home/user/documents/File1.txt

The pwd stands for "print working directory" and prints the current working directory. In the above code, the $ pwd prints the current working directory to the console, documents in this -example.

The $ relative_path variable represents the file’s relative path we want to get the absolute path for. Then the absolute_path variable assigns the value of the current working directory (obtained by running pwd) concatenated with the file’s relative path. Next, the concatenation separates the directory and file names using the / character. And finally, the output is displayed on the console using the $ echo command.

Using cd Command

Use the cd command to get an absolute path from a relative path in Bash.

pwd
relative_path="documents/File1.txt"
cd $(dirname $relative_path) && absolute_path="$(pwd)/$(basename $relative_path)"
echo $absolute_path
cd -
/home/user/documents/File1.txt

The cd command is more robust than the pwd command, as it resolves symbolic links and returns the canonical absolute path. The above code fence is similar to the previous one but uses the cd command along with the dirname command to change the current working directory to the directory containing the file. This is done so that the pwd command can be used to obtain the file’s absolute path, which is then stored in a variable absolute_path.

The basename extracts the file name from the relative path and appends it to the current working directory obtained by the pwd command. Next, the absolute path is printed to the console using the echo command. Finally, the cd - command is executed to return to the previous working directory.

Considering the above solutions, obtaining the absolute path of a file or directory from its relative path is an essential task when working with Bash Script. Each method has its advantages and disadvantages, so it’s up to you to choose the method that best fits your needs. By mastering these methods, you’ll be well-equipped to handle any file system navigation tasks you encounter in your shell scripts.

That’s all about bash get absolute path from relative path.

]]>
https://java2blog.com/bash-get-absolute-path-from-relative-path/feed/ 0