Remove Odd or Even Lines from a Text File

Remove odd or even lines from a text file

awk

The % is a modulus operator and NR is the current line number, so NR%2==0 is true only for even lines and will invoke the default rule for them ({ print $0 }). Thus to save only the even lines, redirect the output from awk to a new file:

awk 'NR%2==0' infile > outfile

sed

You can accomplish the same thing with sed. devnulls answer shows how to do it with GNU sed.
Below are alternatives for versions of sed that do not have the ~ operator:

keep odd lines

sed 'n; d' infile > outfile

keep even lines

sed '1d; n; d' infile > outfile

Bash - Remove odd/even lines based on text match on specific line

Edit: see the clarification of the OP above: when an even line is deleted, the next line becomes even, and the same with odd lines.

Second Edit: according to a further explanation of the OP (he said: "Sorry. I didn't explain myself well. Let me try again. Imagine 'a' is user, and 'b' is address. I want to remove any data where the user only inputted his name but not an address. I only want to keep the completed name/address pairs"), the solution is next command:

awk -F= '$1=="a"{a=$0} (a!="")&&($1=="b"){print a; print; a=""}' input.txt

Output:

a=1
b=2
a=5
b=7

Remove odd lines in a text file

# awk 'NR%2==0' file
http://www.here.is.a.hyper.link.net/
http://www.here.is.another.hyper.link.net/

Delete odd numbered lines in text, skip blank lines

One option would be:

^.+\R(.+)

See an online demo

  • ^ - Start-line anchor;
  • .+\R - Any 1+ characters upto any unicode newlince sequence;
  • (.+) - Capture a 2nd line of 1+ characters in a capture group.

Replace with \1

remove lines that are odd from textfile android

You could do it in another way that probably will save your time and some code lines. You could get all file lines into a list and then it would be much easier to interact with it:

List<String> lines = Files.readAllLines(Paths.get(*path_to_file*), Charset.defaultCharset());

After storing your file lines into List you become able to iterate thro it to search for needed lines. To avoid NullPointerException or IndexOutOfBoundsException don't forget to specify right bounds.

for (int i = 0; i < lines.size() - 1; i++) {
if (lines.get(i).startsWith("#") && !lines.get(i + 1).startsWith("h")) {
lines.remove(i+1);
}
}

After that, you're able to store your List into a file:

Files.write(Paths.get(*path_to_file*), lines);

I tested that and output looked like that:

Sample Image

--- Update ---

To perform IO operations you could use Scanner and FileWriter:

List<String> lines = new ArrayList<>();

Scanner s = new Scanner(new File("in.txt"));

while (s.hasNext()) {
lines.add(s.next());
}

s.close();

And for output:

FileWriter writer = new FileWriter("out.txt");

for (String str : lines) {
writer.write(str + System.lineSeparator());
}

writer.close();

How to remove odd lines except for first line using SED or AWK

Works on GNU sed

sed '3~2d' ip.txt 

This deletes line numbers starting from 3rd line and then +2,+4,+6, etc

Example:

$ seq 10 | sed '3~2d'
1
2
4
6
8
10

How to swap odd and even lines in a text file?

There are several solutions for this task.

The first one uses delayed expansion on execution of all lines of batch file exchanging odd and even lines. This means it does not work right for lines with an exclamation in line because ! is removed from line.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "SourceFile=%USERPROFILE%\Desktop\TestFile.txt"
if not exist "%SourceFile%" goto EndBatch
set "TargetFile=%USERPROFILE%\Desktop\TestFile2.txt"
del "%TargetFile%" 2>nul

set "LineOdd="
for /F "usebackq delims=" %%I in ("%SourceFile%") do (
if not defined LineOdd (
set "LineOdd=%%I"
) else (
echo %%I>>"%TargetFile%"
echo !LineOdd!>>"%TargetFile%"
set "LineOdd="
)
)

if defined LineOdd echo !LineOdd!>>"%TargetFile%"
move /Y "%TargetFile%" "%SourceFile%"

:EndBatch
endlocal

Blank and empty lines are skipped by FOR and therefore missing in target file. And lines starting with a semicolon ; are ignored on reading each line by FOR and for that reason are missing also in output file. But those limitations should not matter here according to input example.

The limitations of first solution could be avoided using this batch code which is of course much slower:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=%USERPROFILE%\Desktop\TestFile.txt"
if not exist "%SourceFile%" goto EndBatch
set "TargetFile=%USERPROFILE%\Desktop\TestFile2.txt"
del "%TargetFile%" 2>nul

set "LineOdd="
for /F "tokens=1* delims=:" %%H in ('%SystemRoot%\System32\findstr.exe /N /R "^" "%SourceFile%"') do (
if not defined LineOdd (
set "LineOdd=_%%I"
) else (
if "%%I" == "" (
echo/>>"%TargetFile%"
) else (
echo %%I>>"%TargetFile%"
)
setlocal EnableDelayedExpansion
if "!LineOdd!" == "_" (
echo/>>"%TargetFile%"
) else (
echo !LineOdd:~1!>>"%TargetFile%"
)
endlocal
set "LineOdd="
)
)

if defined LineOdd (
setlocal EnableDelayedExpansion
if "!LineOdd!" == "_" (
echo/>>"%TargetFile%"
) else (
echo !LineOdd:~1!>>"%TargetFile%"
)
endlocal
)
move /Y "%TargetFile%" "%SourceFile%"

:EndBatch
endlocal

It would be also possible to use hybrid batch file JREPL.BAT written by Dave Benham:

call jrepl.bat "^(.*)\r\n(.*)\r\n" "$2\r\n$1\r\n" /M /X /F "%USERPROFILE%\Desktop\TestFile.txt" /O "%USERPROFILE%\Desktop\TestFile2.txt"
move /Y "%USERPROFILE%\Desktop\TestFile2.txt" "%USERPROFILE%\Desktop\TestFile.txt"

The last line of the file must have a DOS/Windows line termination (carriage return \r and line-feed \n) if being an even line on using this solution.

For understanding the used commands/executables/batch files and how they work, open a command prompt window, execute there the following command lines, and read entirely all help pages displayed for each command/executable/batch file very carefully.

  • del /?
  • echo /?
  • endlocal /?
  • findstr.exe /?
  • for /?
  • goto /?
  • if /?
  • jrepl.bat /?
  • move /?
  • set /?
  • setlocal /?

Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul and >>.

How to remove duplicate strings with odd index line and next even string in text file and avoid it for evens

Samples: Simple | Extended

Code:

string[] lines = System.IO.File.ReadAllLines("/path/to/file.txt");
List<string> newLines = new List<string>();
for(int x = 0; x < lines.Length; x++)
{
if(x % 2 == 1 && newLines.Contains(lines[x])) //is odd and already exists
x++; \\skip next even line
else
newLines.Add(lines[x]);
}

Read and Write Line by Line - Code:

//Delete file if exists
if(System.IO.File.Exists(@"/path/to/new_file.txt"))
System.IO.File.Delete(@"/path/to/new_file.txt")

List<string> newLines = new List<string>();
using (System.IO.StreamReader file = new System.IO.StreamReader(@"/path/to/file.txt"))
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(@"/path/to/new_file.txt", true))
{
string line = null;
int x = 0;
while((line = file.ReadLine()) != null)
{
if(x % 2 == 1 && newLines.Contains(line)) //is odd and already exists
x++; \\skip next even line
else
{
newLines.Add(line);
writer.WriteLine(line);
}
x++;
}
}

Results should be:

+EVEN: some text 1
+ODD: some text 2
+EVEN: some text 3
-ODD: some text 2
-EVEN: some text 5
+ODD: some text 6
+EVEN: some text 2
+ODD: some text 7
+EVEN: some text 2
+ODD: some text 9

How to skip first line and delete odd lines

you can use awk

awk 'NR==1 || !(NR%2)' file

or gnu-sed

sed -n '1p; 2~2p' file

or

sed '3~2d' file


Related Topics



Leave a reply



Submit