Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Linux- removes blank lines from text and files

Shulou Source: shulou.com Published: 2022-06-01 07:04:15 09月15日 Update

Delete blank lines in text or files

Lab description:

Can process one or more files at the same time

It is required to verify the existence of the file before deleting blank lines with sed

The output of sed is imported into a temporary file with $$in the file name, and finally the temporary file is moved back to the original file.

Use the shift command to get all the file names, and use the while loop to process all the files one by one until they are finished

You can get a short help message using del.lines-- help.

The process of the experiment:

1: write a script called del.lines:

The screenshot is as follows:

The contents are as follows:

#! / bin/bash

# Script takes filename (s) and deletes all blank lines.

TEMP_F= "/ tmp/del.lines.$$"

Usage ()

{

Echo "Usage:$0 file [file...]"

Echo "try $0-help for more info"

Exit 1

}

If [$#-eq 0]

Then

Usage

Fi

FILES=$1

While [$#-gt 0]

Do

Echo "... $1"

Case $1 in

-- help)

Echo "Use this script to delete all blank lines from a text file (s)"

Exit 0

*)

FILE_NAME=$1

If [- f $1]

Then

Sed'/ ^ $/ d'$FILE_NAME > $TEMP_F

Mv $TEMP_F $FILE_NAME

Else

Echo "$0 cannot find this file: $1"

Fi

Shift

Esac

Done

two。 Save the script and increase the execution permission: chmod + x del.lines. After execution, the script prompts for help:

3. To verify the execution of the script:

Add two useless data script files with blank lines:

The screenshot of the file content is as follows:

4. Execute the script and verify the effect:

Notes:

The basename command separates the file name from the path. Commonly used in shell scripts

The shift statement is used to migrate location variables, passing $1 percent 9 to the left in turn.

Eg:

If the current script gets the following location variables:

$1=file1, $2=file2, $3=file3, $4=file4

After executing the shift command once, the setting variables are:

$1=file2, $2=file3, $3=file4

After executing the shift command again, the setting variables are:

$1=file3, $2=file4

. . .

5. Modify the script according to the actual environment in order to serve the production environment.

Welcome to the official account of Wechat: Xiao Wen study Society.

Tags: File script location variable command blank line file name processing content screenshot effect environment experiment help validation text short two information public Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Information Xiaomi Huawei Docker